SpreadJS基于HTML5和jQuery技术,通过画布呈现在客户端。类似Excel的风格外观和用户界面行为为最终用户提供了丰富的、可交互的用户体验。本文主要介绍 SpreadJS在服务器端导入导出Excel的使用方法。
1.在aspx页面内添加导入导出代码
protected void ImportBtn_Click(object sender, EventArgs e){string uriString = "http://localhost/ExcelIO/xsapi/import";
System.Net.WebClient myWebClient = new System.Net.WebClient();
string fileName = MapPath("Test.xls");
byte[] responseArray = myWebClient.UploadFile(uriString, "POST", fileName);string spreadjsJsonResult = System.Text.Encoding.UTF8.GetString(responseArray);HiddenField1.Value = spreadjsJsonResult;}protected void ExportBtn_Click(object sender, EventArgs e){using (var stream = File.Create(MapPath("test1.xlsx"))){WebClient request = new WebClient();
System.Collections.Specialized.NameValueCollection formData = new System.Collections.Specialized.NameValueCollection();
formData["type"] = "application/json";formData["data"] = this.HiddenField1.Value;byte[] result = request.UploadValues("http://localhost/ExcelIO/xsapi/export", "POST", formData);stream.Write(result, 0, result.Length);stream.Close();}this.HiddenField1.Value = "";
}
2.前台JS脚本
<script type="text/javascript">
$(document).ready(function () {$("#ss").wijspread();
var spread = $("#ss").wijspread("spread");var sheet = spread.getActiveSheet();
//Import Excel to SpreadJS.
if ($("#HiddenField1").val() != "") {var data = JSON.parse($("#HiddenField1").val());spread.fromJSON(data.spread);}//Export SpreadJS to Excel.
$("#ExportBtn").click(function () {var data = spread.toJSON();
var dataObj = {
"spread": spread.toJSON(),
"exportFileType": "xlsx","excel": {
"saveFlags": 0,
"password": ""
}};var content = JSON.stringify(dataObj);
$("#HiddenField1").val(content);
});});</script>
3.页面文件
<form id="form1" runat="server"><div><div id="ss" style="width: 100%; height: 600px; border: 1px solid gray"></div><asp:Button ID="ImportBtn" runat="server" Text="Import Excel" OnClick="ImportBtn_Click" /><asp:Button ID="ExportBtn" runat="server" Text="Export Excel" OnClick="ExportBtn_Click" /><asp:HiddenField ID="HiddenField1" runat="server" /></div></form>