标签:
首先,只能在ie浏览器下使用才可以,因为要调用excel控件,别的浏览器不行;
其次,要对浏览器进行安全设置的更改:
internet选项-安全-自定义安全级别-将文件上载到服务器时包含本地目录路径(启用)
internet选项-安全-自定义安全级别-对未标记为可安全执行脚本的ActiveX控件初始化并执行脚本(启用)
html页面:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title> New Document </title> <meta name="Generator" content="EditPlus"/> <meta name="Author" content=""/> <meta name="Keywords" content=""/> <meta name="Description" content=""/> <script src="Scripts/jquery-1.12.2.js" type="text/javascript"></script> <script type="text/javascript"> var tempStr=""; function ReadExcel() { tempStr = ""; //得到文件路径的值 var filePath = document.getElementById("upfile").value; //创建操作EXCEL应用程序的实例 var oXL = new ActiveXObject("Excel.application"); //打开指定路径的excel文件 var oWB = oXL.Workbooks.open(filePath); //操作第一个sheet(从一开始,而非零) oWB.worksheets(1).select(); var oSheet = oWB.ActiveSheet; //使用的行数 var rows = oSheet.usedrange.rows.count; var columns = oSheet.usedrange.columns.count; tempStr += '{"rows":['; try{ for (var i = 0; i < rows; i++) { tempStr += '['; for (var j = 0; j < columns; j++) { tempStr += '"'; if ((oSheet.Cells(i + 1, j + 1) + "") != "undefined") { tempStr += (oSheet.Cells(i + 1, j + 1)+""); } else { tempStr += ("{-}"); } tempStr += '"'; if (columns != (j + 1)) { tempStr += ','; } } if (rows != i + 1) tempStr += '],'; else tempStr += ']'; } tempStr += ']}'; }catch(e) { document.getElementById("txtArea").value = tempStr; } document.getElementById("txtArea").value = tempStr; //退出操作excel的实例对象 oXL.Application.Quit(); //手动调用垃圾收集器 CollectGarbage(); } function uploadJson() { $.post("UploadPost.aspx", {jsonstr:tempStr}, function (data, status) {alert("Data:"+data+"\nStatus:"+status) }); } </script> </head> <body> <input type="file" id="upfile"/><input type="button" onclick="ReadExcel();" value="read"/><input type="button" value="uploadJson" onclick="uploadJson()"/> <br/> <textarea id="txtArea" cols="100" rows="50"></textarea> </body> </html>
上传到服务器:
UploadPost.aspx.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.IO; using Newtonsoft.Json; using Newtonsoft.Json.Linq; public partial class UploadPost : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { string str = Request.Form["jsonstr"]; string str2 = ""; JObject jo = (JObject)JsonConvert.DeserializeObject(str); for (int i = 0; i < jo["rows"].Count(); i++) { for (int j = 0; j < jo["rows"][i].Count(); j++) { str2 += jo["rows"][i][j]; str2 += " "; } str2 += "\n"; } Response.Clear(); Response.ContentType = "text/plain"; Response.Write(str2); Response.End(); } }
标签:
原文地址:http://blog.csdn.net/wzj0808/article/details/51372049