实现功能


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

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

客户端(Test.aspx)


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

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

 <div id="loadingDiv"><div id="loadingCont"><img src="assets/loading.gif"/><span style="">请稍等...</span></div></div>
<a id="downfile"><span></span></a> <div class="col-md-2 col-xs-4">
<button class="btn btn-info" id="tab2-btn-import"><img src="assets/计算四参数.png"/><i class="icon-reply"></i>导入</button>
<input type="file" name="file" id="upload-file" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"/>
</div> <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:;
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:;
left:calc(50% - 40px);
cursor:pointer;
opacity:;
}

css

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

     //Uploadify
//导入
$("#upload-file").change(ImportExcel);
function ImportExcel() {
$("#loadingDiv").show(); //显示加载控件;
$.ajaxFileUpload(
{
url: 'Test.aspx', //用于文件上传的服务器端请求地址
secureuri: false, //是否需要安全协议,一般设置为false
fileElementId: 'upload-file', //文件上传域的ID
dataType: 'JSON', //返回值类型 一般设置为json
success: function (data, status) //服务器成功响应处理函数
{
if (status == "success") {
try {
var jsondata = $.parseJSON(data);
if (jsondata[0]["源坐标X"] == undefined || jsondata[0]["源坐标Y"] == undefined || jsondata[0]["目标坐标X"] == undefined || jsondata[0]["目标坐标Y"] == undefined) {
alert("Excel格式有误,请按标准格式导入");
}
else {
var rows_be = grid.count();
for (var i = 1; i <= rows_be ; i++) {
grid.removeRow(i); //grid.clear()不会清空,再使用addRow时仍会显示之前数据,暂时解决办法为暴力清空
}
for (var i = 0; i < jsondata.length; i++) {
grid.addRow({ '点名': jsondata[i]["点名"], "源坐标X": jsondata[i]["源坐标X"], "源坐标Y": jsondata[i]["源坐标Y"], "目标坐标X": jsondata[i]["目标坐标X"], "目标坐标Y": jsondata[i]["目标坐标Y"] });
}
}
}
catch (e) {
console.log(e);
alert("Excel格式有误,请按标准格式导入");
}
finally {
$("#upload-file").change(ImportExcel); //ajaxFileUpload插件执行完成会新建,需要重新绑定事件
$("#loadingDiv").hide(); //数据准备完成,隐藏加载控件
}
}
},
error: function (data, status, e)//服务器响应失败处理函数
{
console.log(e);
$("#loadingDiv").hide();
}
});
} //hover时显示提示
$("#upload-file").hover(function () { $("#tab2-btn-import img").show(); }, function () { $("#tab2-btn-import img").hide(); }); //导出
$("#tab2-btn-export").on("click", ExportExcel);
function ExportExcel() {
$("#loadingDiv").show();
$.ajax({
type: 'post',
url: 'Test.aspx/Export2Excel',
data: "{'RowData':'" + JSON.stringify(grid.getAll()) + "'}",
dataType: 'json',
contentType: 'application/json;charset=utf-8',
success: function (data) {
console.log(data);
if (data.d == "") {
alert("该时段无历史数据");
}
else {
var jsondata = $.parseJSON(data.d);
if (jsondata["result"] != "fail") downloadFile(window.location.host + "\\文件路径,此处隐藏\\" + jsondata["result"]);
}
$("#loadingDiv").hide();
},
error: function (msg) {
console.log(msg);
$("#loadingDiv").hide();
}
});
}
});
//自动下载文件
function downloadFile(docurl) {
$("#downfile").attr("href", "http://" + docurl);
$("#downfile span").click();
}

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

 jQuery.extend({

     createUploadIframe: function(id, uri)
{
//create frame
var frameId = 'jUploadFrame' + id; if(window.ActiveXObject) {
var io = document.createElement('<iframe id="' + frameId + '" name="' + frameId + '" />');
if(typeof uri== 'boolean'){
io.src = 'javascript:false';
}
else if(typeof uri== 'string'){
io.src = uri;
}
}
else {
var io = document.createElement('iframe');
io.id = frameId;
io.name = frameId;
}
io.style.position = 'absolute';
io.style.top = '-1000px';
io.style.left = '-1000px'; document.body.appendChild(io); return io
},
createUploadForm: function(id, fileElementId)
{
//create form
var formId = 'jUploadForm' + id;
var fileId = 'jUploadFile' + id;
var form = $('<form action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');
var oldElement = $('#' + fileElementId);
var newElement = $(oldElement).clone();
$(oldElement).attr('id', fileId);
$(oldElement).before(newElement);
$(oldElement).appendTo(form);
//set attributes
$(form).css('position', 'absolute');
$(form).css('top', '-1200px');
$(form).css('left', '-1200px');
$(form).appendTo('body');
return form;
},
addOtherRequestsToForm: function(form,data)
{
// add extra parameter
var originalElement = $('<input type="hidden" name="" value="">');
for (var key in data) {
name = key;
value = data[key];
var cloneElement = originalElement.clone();
cloneElement.attr({'name':name,'value':value});
$(cloneElement).appendTo(form);
}
return form;
}, ajaxFileUpload: function(s) {
// TODO introduce global settings, allowing the client to modify them for all requests, not only timeout
s = jQuery.extend({}, jQuery.ajaxSettings, s);
var id = new Date().getTime()
var form = jQuery.createUploadForm(id, s.fileElementId);
if ( s.data ) form = jQuery.addOtherRequestsToForm(form,s.data);
var io = jQuery.createUploadIframe(id, s.secureuri);
var frameId = 'jUploadFrame' + id;
var formId = 'jUploadForm' + id;
// Watch for a new set of requests
if ( s.global && ! jQuery.active++ )
{
jQuery.event.trigger( "ajaxStart" );
}
var requestDone = false;
// Create the request object
var xml = {}
if ( s.global )
jQuery.event.trigger("ajaxSend", [xml, s]);
// Wait for a response to come back
var uploadCallback = function(isTimeout)
{
var io = document.getElementById(frameId);
try
{
if(io.contentWindow)
{
xml.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null;
xml.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document; }else if(io.contentDocument)
{
xml.responseText = io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:null;
xml.responseXML = io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document;
}
}catch(e)
{
jQuery.handleError(s, xml, null, e);
}
if ( xml || isTimeout == "timeout")
{
requestDone = true;
var status;
try {
status = isTimeout != "timeout" ? "success" : "error";
// Make sure that the request was successful or notmodified
if ( status != "error" )
{
// process the data (runs the xml through httpData regardless of callback)
var data = jQuery.uploadHttpData( xml, s.dataType );
// If a local callback was specified, fire it and pass it the data
if ( s.success )
s.success( data, status ); // Fire the global callback
if( s.global )
jQuery.event.trigger( "ajaxSuccess", [xml, s] );
} else
jQuery.handleError(s, xml, status);
} catch(e)
{
status = "error";
jQuery.handleError(s, xml, status, e);
} // The request was completed
if( s.global )
jQuery.event.trigger( "ajaxComplete", [xml, s] ); // Handle the global AJAX counter
if ( s.global && ! --jQuery.active )
jQuery.event.trigger( "ajaxStop" ); // Process result
if ( s.complete )
s.complete(xml, status); jQuery(io).unbind() setTimeout(function()
{ try
{
$(io).remove();
$(form).remove(); } catch(e)
{
jQuery.handleError(s, xml, null, e);
} }, 100) xml = null }
}
// Timeout checker
if ( s.timeout > 0 )
{
setTimeout(function(){
// Check to see if the request is still happening
if( !requestDone ) uploadCallback( "timeout" );
}, s.timeout);
}
try
{
// var io = $('#' + frameId);
var form = $('#' + formId);
$(form).attr('action', s.url);
$(form).attr('method', 'POST');
$(form).attr('target', frameId);
if(form.encoding)
{
form.encoding = 'multipart/form-data';
}
else
{
form.enctype = 'multipart/form-data';
}
$(form).submit(); } catch(e)
{
jQuery.handleError(s, xml, null, e);
}
if(window.attachEvent){
document.getElementById(frameId).attachEvent('onload', uploadCallback);
}
else{
document.getElementById(frameId).addEventListener('load', uploadCallback, false);
}
return {abort: function () {}}; }, uploadHttpData: function( r, type ) {
var data = !type;
data = type == "xml" || data ? r.responseXML : r.responseText;
// If the type is "script", eval it in global context
if ( type == "script" )
jQuery.globalEval( data );
// Get the JavaScript object, if JSON is used.
if ( type == "json" )
{
// If you add mimetype in your response,
// you have to delete the '<pre></pre>' tag.
// The pre tag in Chrome has attribute, so have to use regex to remove
var data = r.responseText;
var rx = new RegExp("<pre.*?>(.*?)</pre>","i");
var am = rx.exec(data);
//this is the desired data extracted
var data = (am) ? am[1] : ""; //the only submatch or empty
eval( "data = " + data );
}
// evaluate scripts within html
if ( type == "html" )
jQuery("<div>").html(data).evalScripts();
//alert($('param', data).each(function(){alert($(this).attr('value'));}));
return data;
}, handleError: function( s, xhr, status, e ) {
// If a local callback was specified, fire it
if ( s.error ) {
s.error.call( s.context || s, xhr, status, e );
} // Fire the global callback
if ( s.global ) {
(s.context ? jQuery(s.context) : jQuery.event).trigger( "ajaxError", [xhr, s, e] );
}
}
})

ajaxfileupload.js

服务端(Test.aspx.cs)


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

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

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

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

以下为服务端代码:

     protected void Page_Load(object sender, EventArgs e)
{
HttpFileCollection files = Request.Files;
string msg = string.Empty;
string error = string.Empty;
//string docurl;
if (files.Count > )
{
string path = Server.MapPath("~/项目目录/uploadfile/") + Path.GetFileName(files[].FileName); files[].SaveAs(path);
//msg = "成功!文件大小为:" + files[0].ContentLength; //解析Excel
string excelgrid = "";
using (ExcelHelper excelHelper = new ExcelHelper(path))
{
DataTable dt = excelHelper.ExcelToDataTable("MySheet", true);
excelgrid = JsonHepler.ToJson(dt);
}
//string res = "{ error:'" + error + "', msg:'" + msg + "',excelgrid:'" + excelgrid + "'}";
Response.Write(excelgrid);
Response.End();
}
} [WebMethod]
public static string Export2Excel(string RowData)
{
try
{
DataTable dt = JsonHepler.JsonToDataTable(RowData);
string docname = string.Format("{0:yyyyMMddHHmmssffff}", DateTime.Now) + ".xlsx";
string docurl = AppDomain.CurrentDomain.BaseDirectory + "项目目录\\downloadfile\\" + docname;
int count = ; using (ExcelHelper excelHelper = new ExcelHelper(docurl))
{
count = excelHelper.DataTableToExcel(dt,"MySheet", true);
} if (count >= ) return "{\"result\":\""+ docname + "\"}";
else return "{'result':'fail'}";
}
catch(Exception)
{
throw;
}
}

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

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

JS异步上传Excel 并使用NPOI进行读写操作的更多相关文章

  1. 利用ajaxfileupload.js异步上传文件

    1.引入ajaxfileupload.js 2.html代码 <input type="file" id="enclosure" name="e ...

  2. ajaxfileupload.js异步上传

    转载:https://www.cnblogs.com/labimeilexin/p/6742647.html jQuery插件之ajaxFileUpload     ajaxFileUpload.js ...

  3. 关于JQuery.form.js异步上传文件点滴

    好久没动代码了,前几天朋友委托我帮忙给做几个页面,其中有个注册带图片上传的页面.已之前的经验应该很快就能搞定,没想到的是搞了前后近一天时间.下面就说说异步上传的重要几个点,希望自己下次遇到此类问题的时 ...

  4. JS异步上传文件

    直接调用Upload(option)方法,即可上传文件,不需要额外的插件辅助,采用原生js编写. /* *异步上传文件 *option参数 **url:上传路径 **data:上传的其他数据{id:& ...

  5. 关于js异步上传文件

    好久没登录博客园了,今天来一发分享. 最近项目里有个需求,上传文件(好吧,这种需求很常见,这也不是第一次遇到了).当时第一想法就是直接用form表单提交(原谅我以前就是这么干的),不过表单里不仅有文件 ...

  6. ASP.NET MVC 使用jquery.form.js 异步上传 在IE下返回值被变为下载的解决办法

    错误记录: <script type="text/javascript"> $(function () { $(document).off("ajaxSend ...

  7. Node.js——异步上传文件

    前台代码 submit() { var file = this.$refs.fileUpload.files[0]; var formData = new FormData(); formData.a ...

  8. Js异步上传加进度条

    http://www.ruanyifeng.com/blog/2012/09/xmlhttprequest_level_2.html http://www.cnblogs.com/yuanlong10 ...

  9. vue.js异步上传文件前后端代码

    上传文件前端代码如下: <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type&q ...

随机推荐

  1. Apple开启双重认证过程

    1.准备 1.1 AppleID账号.密码 1.2 打算用于接收开启双重认证的十一位手机号 1.3 AppleID账号密保问题 2.操作步骤: 2.1 打开设置 2.2 点击个人账户头像 注意:当前有 ...

  2. 同一个程序里有多个版本的App

    在Xcode中添加多个targets进行版本控制,就是同一个app开发多个版本 以Xcode 9.3 为例 1. 创建 点击左侧工程项目文件,选择TARGETS 下的项目右击选择 Duplicate. ...

  3. OOP3(继承中的类作用域/构造函数与拷贝控制/继承与容器)

    当存在继承关系时,派生类的作用域嵌套在其基类的作用域之内.如果一个名字在派生类的作用域内无法正确解析,则编译器将继续在外层的基类作用域中寻找该名字的定义 在编译时进行名字查找: 一个对象.引用或指针的 ...

  4. uoj #298. 【CTSC2017】网络

    #298. [CTSC2017]网络 一个一般的网络系统可以被描述成一张无向连通图.图上的每个节点为一个服务器,连接服务器与服务器的数据线则看作图上的一条边,边权为该数据线的长度.两个服务器之间的通讯 ...

  5. Python 简单说明与数据结构

    Python 简单说明与数据结构 Python 作为 "国内" 较流行的高级语言,具有代码容易理解.专注解决问题.混合编译其他语言的优点. 变量 变量是一个最基本的储存单位,它暂时 ...

  6. 【数据结构】单链表&&静态链表详解和代码实例

    喜欢的话可以扫码关注我们的公众号哦,更多精彩尽在微信公众号[程序猿声] 01 单链表(Singly Linked List ) 1.1 什么是单链表? 单链表是一种链式存储的结构.它动态的为节点分配存 ...

  7. 怎样关闭adobe reader的自动更新

    https://jingyan.baidu.com/article/1612d5004390ebe20f1eee50.html

  8. mvc 请求处理管道

    原文 http://blog.csdn.net/wulex/article/details/41514795 当一个asp.net mvc应用程序提出请求,为了响应请求,包含一些请求执行流程步骤! 在 ...

  9. Linux磁盘占满 no space left on device

    假如当前文件删除了,如果还有其他进程还在使用这个文件,这个文件删不干净:https://www.cnblogs.com/heyonggang/p/3644736.html 在Linux下查看磁盘空间使 ...

  10. SQL函数:返回传入的字符中的数字或者字符

    /******返回传入的字符串的所有字符 ******/SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOALTER function [dbo].[F_Get ...