首页 > 代码库 > JS异步上传Excel 并使用NPOI进行读写操作

JS异步上传Excel 并使用NPOI进行读写操作

实现功能


 

导入——客户端使用 ajaxfileupload.js 插件实现Excel的异步上传,并在服务端解析成JSON字符串返回页面

导出——将页面中的grid表拼接成JSON串上传至服务器,在服务端新建Excel并将数据导入,随后返回url给用户下载

 

客户端(Test.aspx)


 技术分享

页面上需要实现的效果是显示一个“导入”按钮,hover时会显示标准格式图片,点击触发上传事件,选择Excel文件后上传到服务器,HTML代码如下

PS:使用了Bootstrap样式,也可以自己定义。“loadingDiv”为加载控件,“downfile”存放返回的url,提供下载。附送loading.gif资源,也可以用CSS绘制,可参考我的第一篇博文几个单元素Loading动画解构~

1 <div id="loadingDiv"><div id="loadingCont"><img src="assets/loading.gif"/><span style="">请稍等...</span></div></div>
2 <a id="downfile"><span></span></a>
3 
4 <div class="col-md-2 col-xs-4">
5     <button class="btn btn-info" id="tab2-btn-import"><img src="assets/计算四参数.png"/><i class="icon-reply"></i>导入</button>
6     <input type="file" name="file" id="upload-file" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"/>
7 </div>
8 
9 <div class="col-md-2 col-xs-4"><button class="btn btn-primary" id="tab2-btn-export"><i class="icon-share-alt"></i>导出</button></div>

 

CSS代码如下

技术分享
#loadingDiv{
    width:100%;
    height:100%;
    position:absolute;
    z-index:999;
    display:none;
}
#loadingCont{
    width:130px;
    height:50px; 
    position:relative;
    padding-left:10px;
    left:calc(50% - 50px);
    top:40%;
    border-radius:3px;
    background-color:#fff;
}
#loadingCont img{
    width:50px; 
    height:50px;
}
#loadingCont span{
    position:relative;
    top:2px;
    color: #696969; 
    font-family:"Microsoft YaHei";
}


#tab2-btn-import{
    position:relative;
}
#tab2-btn-import img{
    position:absolute;
    top:-70px;
    left:-145px;
    border:1px solid #999;
    display:none;
}

#upload-file{
    width:80px;
    height:35px;
    position:absolute;
    top:0;
    left:calc(50% - 40px);
    cursor:pointer;
    opacity:0;
}
css

 

实现hover效果和导入、导出的JS代码:

 1     //Uploadify
 2     //导入
 3     $("#upload-file").change(ImportExcel);
 4     function ImportExcel() {
 5         $("#loadingDiv").show();   //显示加载控件;
 6         $.ajaxFileUpload(
 7             {
 8                 url: ‘Test.aspx‘, //用于文件上传的服务器端请求地址
 9                 secureuri: false, //是否需要安全协议,一般设置为false
10                 fileElementId: ‘upload-file‘, //文件上传域的ID
11                 dataType: ‘JSON‘, //返回值类型 一般设置为json
12                 success: function (data, status)  //服务器成功响应处理函数
13                 {
14                     if (status == "success") {
15                         try {
16                             var jsondata =http://www.mamicode.com/ $.parseJSON(data);
17                             if (jsondata[0]["源坐标X"] == undefined || jsondata[0]["源坐标Y"] == undefined || jsondata[0]["目标坐标X"] == undefined || jsondata[0]["目标坐标Y"] == undefined) {
18                                 alert("Excel格式有误,请按标准格式导入");
19                             }
20                             else {
21                                 var rows_be = grid.count();
22                                 for (var i = 1; i <= rows_be ; i++) {
23                                     grid.removeRow(i);   //grid.clear()不会清空,再使用addRow时仍会显示之前数据,暂时解决办法为暴力清空
24                                 }
25                                 for (var i = 0; i < jsondata.length; i++) {
26                                     grid.addRow({ ‘点名‘: jsondata[i]["点名"], "源坐标X": jsondata[i]["源坐标X"], "源坐标Y": jsondata[i]["源坐标Y"], "目标坐标X": jsondata[i]["目标坐标X"], "目标坐标Y": jsondata[i]["目标坐标Y"] });
27                                 }
28                             }
29                         }
30                         catch (e) {
31                             console.log(e);
32                             alert("Excel格式有误,请按标准格式导入");
33                         }
34                         finally {
35                             $("#upload-file").change(ImportExcel);    //ajaxFileUpload插件执行完成会新建,需要重新绑定事件
36                             $("#loadingDiv").hide();   //数据准备完成,隐藏加载控件
37                         }
38                     }
39                 },
40                 error: function (data, status, e)//服务器响应失败处理函数
41                 {
42                     console.log(e);
43                     $("#loadingDiv").hide();
44                 }
45             });
46     }
47 
48     //hover时显示提示
49     $("#upload-file").hover(function () { $("#tab2-btn-import img").show(); }, function () { $("#tab2-btn-import img").hide(); });
50 
51     //导出
52     $("#tab2-btn-export").on("click", ExportExcel);
53     function ExportExcel() {
54         $("#loadingDiv").show();
55         $.ajax({
56             type: ‘post‘,
57             url: ‘Test.aspx/Export2Excel‘,
58             data: "{‘RowData‘:‘" + JSON.stringify(grid.getAll()) + "‘}",
59             dataType: ‘json‘,
60             contentType: ‘application/json;charset=utf-8‘,
61             success: function (data) {
62                 console.log(data);
63                 if (data.d == "") {
64                     alert("该时段无历史数据");
65                 }
66                 else {
67                     var jsondata =http://www.mamicode.com/ $.parseJSON(data.d);
68                     if (jsondata["result"] != "fail") downloadFile(window.location.host + "\\文件路径,此处隐藏\\" + jsondata["result"]);
69                 }
70                 $("#loadingDiv").hide();
71             },
72             error: function (msg) {
73                 console.log(msg);
74                 $("#loadingDiv").hide();
75             }
76         });
77     }
78 });
79 //自动下载文件
80 function downloadFile(docurl) {
81     $("#downfile").attr("href", "http://" + docurl);
82     $("#downfile span").click();
83 }

PS:对于ajaxFileUpload插件的使用可以看看这篇文章jQuery插件之ajaxFileUpload,因为插件代码很短所以在这里贴出来,各位新建一个js文件粘进去即可。

技术分享
  1 jQuery.extend({
  2 
  3 
  4     createUploadIframe: function(id, uri)
  5     {
  6         //create frame
  7         var frameId = ‘jUploadFrame‘ + id;
  8 
  9         if(window.ActiveXObject) {
 10             var io = document.createElement(‘<iframe id="‘ + frameId + ‘" name="‘ + frameId + ‘" />‘);
 11             if(typeof uri== ‘boolean‘){
 12                 io.src = ‘javascript:false‘;
 13             }
 14             else if(typeof uri== ‘string‘){
 15                 io.src =http://www.mamicode.com/ uri;
 16             }
 17         }
 18         else {
 19             var io = document.createElement(‘iframe‘);
 20             io.id = frameId;
 21             io.name = frameId;
 22         }
 23         io.style.position = ‘absolute‘;
 24         io.style.top = ‘-1000px‘;
 25         io.style.left = ‘-1000px‘;
 26 
 27         document.body.appendChild(io);
 28 
 29         return io
 30     },
 31     createUploadForm: function(id, fileElementId)
 32     {
 33         //create form
 34         var formId = ‘jUploadForm‘ + id;
 35         var fileId = ‘jUploadFile‘ + id;
 36         var form = $(‘<form  action="" method="POST" name="‘ + formId + ‘" id="‘ + formId + ‘" enctype="multipart/form-data"></form>‘);
 37         var oldElement = $(‘#‘ + fileElementId);
 38         var newElement = $(oldElement).clone();
 39         $(oldElement).attr(‘id‘, fileId);
 40         $(oldElement).before(newElement);
 41         $(oldElement).appendTo(form);
 42         //set attributes
 43         $(form).css(‘position‘, ‘absolute‘);
 44         $(form).css(‘top‘, ‘-1200px‘);
 45         $(form).css(‘left‘, ‘-1200px‘);
 46         $(form).appendTo(‘body‘);
 47         return form;
 48     },
 49     addOtherRequestsToForm: function(form,data)
 50     {
 51         // add extra parameter
 52         var originalElement = $(‘<input type="hidden" name="" value="">‘);
 53         for (var key in data) {
 54             name = key;
 55             value =http://www.mamicode.com/ data[key];
 56             var cloneElement = originalElement.clone();
 57             cloneElement.attr({‘name‘:name,‘value‘:value});
 58             $(cloneElement).appendTo(form);
 59         }
 60         return form;
 61     },
 62 
 63     ajaxFileUpload: function(s) {
 64         // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout
 65         s = jQuery.extend({}, jQuery.ajaxSettings, s);
 66         var id = new Date().getTime()
 67         var form = jQuery.createUploadForm(id, s.fileElementId);
 68         if ( s.data ) form = jQuery.addOtherRequestsToForm(form,s.data);
 69         var io = jQuery.createUploadIframe(id, s.secureuri);
 70         var frameId = ‘jUploadFrame‘ + id;
 71         var formId = ‘jUploadForm‘ + id;
 72         // Watch for a new set of requests
 73         if ( s.global && ! jQuery.active++ )
 74         {
 75             jQuery.event.trigger( "ajaxStart" );
 76         }
 77         var requestDone = false;
 78         // Create the request object
 79         var xml = {}
 80         if ( s.global )
 81             jQuery.event.trigger("ajaxSend", [xml, s]);
 82         // Wait for a response to come back
 83         var uploadCallback = function(isTimeout)
 84         {
 85             var io = document.getElementById(frameId);
 86             try
 87             {
 88                 if(io.contentWindow)
 89                 {
 90                     xml.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null;
 91                     xml.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document;
 92 
 93                 }else if(io.contentDocument)
 94                 {
 95                     xml.responseText = io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:null;
 96                     xml.responseXML = io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document;
 97                 }
 98             }catch(e)
 99             {
100                 jQuery.handleError(s, xml, null, e);
101             }
102             if ( xml || isTimeout == "timeout")
103             {
104                 requestDone = true;
105                 var status;
106                 try {
107                     status = isTimeout != "timeout" ? "success" : "error";
108                     // Make sure that the request was successful or notmodified
109                     if ( status != "error" )
110                     {
111                         // process the data (runs the xml through httpData regardless of callback)
112                         var data =http://www.mamicode.com/ jQuery.uploadHttpData( xml, s.dataType );
113                         // If a local callback was specified, fire it and pass it the data
114                         if ( s.success )
115                             s.success( data, status );
116 
117                         // Fire the global callback
118                         if( s.global )
119                             jQuery.event.trigger( "ajaxSuccess", [xml, s] );
120                     } else
121                         jQuery.handleError(s, xml, status);
122                 } catch(e)
123                 {
124                     status = "error";
125                     jQuery.handleError(s, xml, status, e);
126                 }
127 
128                 // The request was completed
129                 if( s.global )
130                     jQuery.event.trigger( "ajaxComplete", [xml, s] );
131 
132                 // Handle the global AJAX counter
133                 if ( s.global && ! --jQuery.active )
134                     jQuery.event.trigger( "ajaxStop" );
135 
136                 // Process result
137                 if ( s.complete )
138                     s.complete(xml, status);
139 
140                 jQuery(io).unbind()
141 
142                 setTimeout(function()
143                 {    try
144                     {
145                         $(io).remove();
146                         $(form).remove();
147 
148                     } catch(e)
149                     {
150                         jQuery.handleError(s, xml, null, e);
151                     }
152 
153                 }, 100)
154 
155                 xml = null
156 
157             }
158         }
159         // Timeout checker
160         if ( s.timeout > 0 )
161         {
162             setTimeout(function(){
163                 // Check to see if the request is still happening
164                 if( !requestDone ) uploadCallback( "timeout" );
165             }, s.timeout);
166         }
167         try
168         {
169             // var io = $(‘#‘ + frameId);
170             var form = $(‘#‘ + formId);
171             $(form).attr(‘action‘, s.url);
172             $(form).attr(‘method‘, ‘POST‘);
173             $(form).attr(‘target‘, frameId);
174             if(form.encoding)
175             {
176                 form.encoding = ‘multipart/form-data‘;
177             }
178             else
179             {
180                 form.enctype = ‘multipart/form-data‘;
181             }
182             $(form).submit();
183 
184         } catch(e)
185         {
186             jQuery.handleError(s, xml, null, e);
187         }
188         if(window.attachEvent){
189             document.getElementById(frameId).attachEvent(‘onload‘, uploadCallback);
190         }
191         else{
192             document.getElementById(frameId).addEventListener(‘load‘, uploadCallback, false);
193         }
194         return {abort: function () {}};
195 
196     },
197 
198     uploadHttpData: function( r, type ) {
199         var data = http://www.mamicode.com/!type;
200         data = http://www.mamicode.com/type =="xml" || data ? r.responseXML : r.responseText;
201         // If the type is "script", eval it in global context
202         if ( type == "script" )
203             jQuery.globalEval( data );
204         // Get the JavaScript object, if JSON is used.
205         if ( type == "json" )
206         {
207             // If you add mimetype in your response,
208             // you have to delete the ‘<pre></pre>‘ tag.
209             // The pre tag in Chrome has attribute, so have to use regex to remove
210             var data =http://www.mamicode.com/ r.responseText;
211             var rx = new RegExp("<pre.*?>(.*?)</pre>","i");
212             var am = rx.exec(data);
213             //this is the desired data extracted
214             var data = http://www.mamicode.com/(am) ? am[1] :"";    //the only submatch or empty
215             eval( "data = "http://www.mamicode.com/+ data );
216         }
217         // evaluate scripts within html
218         if ( type == "html" )
219             jQuery("<div>").html(data).evalScripts();
220         //alert($(‘param‘, data).each(function(){alert($(this).attr(‘value‘));}));
221         return data;
222     },
223 
224     handleError: function( s, xhr, status, e )      {  
225         // If a local callback was specified, fire it  
226     if ( s.error ) {  
227         s.error.call( s.context || s, xhr, status, e );  
228     }  
229   
230         // Fire the global callback  
231     if ( s.global ) {  
232         (s.context ? jQuery(s.context) : jQuery.event).trigger( "ajaxError", [xhr, s, e] );  
233     }  
234 }  
235 })
ajaxfileupload.js

 

服务端(Test.aspx.cs)


 在服务端做Excel解析常用的有三种方法:

一是使用微软的开放式数据库接口技术OleDb,建立连接后可像数据库一样操作Excel,但是个人测试发现在网页文件上传成功后,OleDb接口无法读取文件,页面报跨域错误(本机调试通过,发布后报错),但路径却是同源的,一直不知道问题在哪儿,希望有了解的前辈指点指点。

二是使用Com组件方式读取,这种方式也尝试过,读取速度相对来说非常慢,故舍弃。

三是使用第三方的NPOI插件。因为前两种方法依赖于微软的Office环境,所以在使用时需要在服务器上安装Office,而这种方法只要下载并引用dll文件即可,优势明显。并且个人测试效率也很高,使用方便,故采用。

 

以下为服务端代码:

 1     protected void Page_Load(object sender, EventArgs e)
 2     {
 3         HttpFileCollection files = Request.Files;
 4         string msg = string.Empty;
 5         string error = string.Empty;
 6         //string docurl;
 7         if (files.Count > 0)
 8         {
 9             string path = Server.MapPath("~/项目目录/uploadfile/") + Path.GetFileName(files[0].FileName);
10 
11             files[0].SaveAs(path);
12             //msg = "成功!文件大小为:" + files[0].ContentLength;
13 
14             //解析Excel  
15             string excelgrid = "";
16             using (ExcelHelper excelHelper = new ExcelHelper(path))
17             {
18                 DataTable dt = excelHelper.ExcelToDataTable("MySheet", true);
19                 excelgrid = JsonHepler.ToJson(dt);
20             }
21             //string res = "{ error:‘" + error + "‘, msg:‘" + msg + "‘,excelgrid:‘" + excelgrid + "‘}";
22             Response.Write(excelgrid);
23             Response.End();
24         }
25     }
26 
27 
28     [WebMethod]
29     public static string Export2Excel(string RowData)
30     {
31         try
32         {
33             DataTable dt = JsonHepler.JsonToDataTable(RowData);
34             string docname = string.Format("{0:yyyyMMddHHmmssffff}", DateTime.Now) + ".xlsx";
35             string docurl = AppDomain.CurrentDomain.BaseDirectory + "项目目录\\downloadfile\\" + docname;
36             int count = 0;
37 
38             using (ExcelHelper excelHelper = new ExcelHelper(docurl))
39             {
40                 count = excelHelper.DataTableToExcel(dt,"MySheet", true);
41             }
42 
43             if (count >= 0) return "{\"result\":\""+ docname + "\"}";
44             else return "{‘result‘:‘fail‘}";
45         }
46         catch(Exception)
47         {
48             throw;
49         }
50     }

NPOI为第三方插件,关于NPOI的使用可以参考NPOI读写Excel,文章中也提供了读取/写入的工具类。同时提供NPOI的下载地址,下载后根据.net版本引入dll即可,在此我使用的是4.0,所以引用了 Net40 文件夹中的数个dll。

接下来我们就可以调试发布啦~

 

JS异步上传Excel 并使用NPOI进行读写操作