MVC异步 导入excel文件
View页面 js文件。封装到一个js文件里面
(function ($) {
//可以忽略
var defaultSettings = {
url: "http://upload.zhtxw.cn/UploadImage.ashx", //上传地址
buttonFeature: true, //true:点击按钮时仅选择文件; false:选择完文件后立即上传
fileSuffixs: ["jpg", "png"], //允许上传的文件后缀名列表
errorText: "不能上传后缀为 {0} 的文件!", //错误提示文本,其中{0}将会被上传文件的后缀名替换
onCheckUpload: function (text) { //上传时检查文件后缀名不包含在fileSuffixs属性中时触发的回调函数,(text为错误提示文本)
alert("不能上传后缀为 " + text + " 的文件");
return false;
},
onComplete: function (msg) {
//上传完成后的回调函数[不管成功或失败,它都将被触发](msg为服务端的返回字符串)
},
onChosen: function (file, obj) { //选择文件后的回调函数,(file为选中文件的本地路径;obj为当前的上传控件实例)
//alert(file);
},
maximumFilesUpload: 5,//最大文件上传数(当此属性大于1时,buttonFeature属性只能为true)
onSubmitHandle: function (uploadFileNumber) { //提交上传时的回调函数,uploadFileNumber为当前上传的文件数量
//在此回调中返回false上传提交将被阻止
return true;
},
onSameFilesHandle: function (file) { //当重复选择相同的文件时触发
//在此回调中返回false当前选择的文件将从上传队列中取消
return true;
},
perviewImageElementId: "",//用于预览上传图片的元素id(请传入一个div元素的id)
perviewImgStyle: null//用于设置图片预览时的样式(可不设置,在不设置的情况下多文件上传时只能显示一张图片),如{ width: '100px', height: '100px', border: '1px solid #ebebeb' }
};
$.fn.uploadFile = function (settings) {
settings = $.extend({}, defaultSettings, settings || {});
if (settings.perviewImageElementId) {
//设置图片预览元素的必须样式
if (!settings.perviewImgStyle) {
var perviewImg = document.getElementById(settings.perviewImageElementId);
perviewImg.style.overflow = "hidden";
}
}
return this.each(function () {
var self = $(this);
var upload = new UploadAssist(settings);
upload.createIframe(this);
//绑定当前按钮点击事件
self.bind("click", function (e) {
upload.chooseFile();
});
//将上传辅助类的实例,存放到当前对象中,方便外部获取
self.data("uploadFileData", upload);
//创建的iframe中的那个iframe,它的事件需要延迟绑定
window.setTimeout(function () {
//为创建的iframe内部的iframe绑定load事件
$(upload.getIframeContentDocument().body.lastChild).load(function () {
var dcmt = upload.getInsideIframeContentDocument();
if (dcmt.body.innerHTML) {
if (settings.onComplete) {
settings.onComplete(dcmt.body.innerHTML);
}
dcmt.body.innerHTML = "";
}
});
}, 100);
});
};
})(jQuery);
//上传辅助类
function UploadAssist(settings) {
//保存设置
this.settings = settings;
//已选择文件的路径集合
this.choseFilePath = [];
//创建的iframe唯一名称
this.iframeName = "upload" + this.getInputFileName();
return this;
}
UploadAssist.prototype = {
//辅助类构造器
constructor: UploadAssist,
//创建iframe
createIframe: function (elem) {
var html = "<html> "
+ " <head> "
+ "<title>upload</title>"
+ "<script>"
+ "function getDCMT(){return window.frames['dynamic_creation_upload_iframe'].document;}"
+ "</" + "script>"
+ "</head>"
+ "<body>"
+ "<form method='post' target='dynamic_creation_upload_iframe' enctype='multipart/form-data' action='" + this.settings.url + "'>"
+ "</form>"
+ "<iframe name='dynamic_creation_upload_iframe'></iframe>"
+ "</body>"
+ "</html>";
this.iframe = $("<iframe name='" + this.iframeName + "'></iframe>")[0];
this.iframe.style.width = "0px";
this.iframe.style.height = "0px";
this.iframe.style.border = "0px solid #fff";
this.iframe.style.margin = "0px";
this.iframe.style.display = "none";
elem.parentNode.insertBefore(this.iframe, elem);
var iframeDocument = this.getIframeContentDocument();
iframeDocument.write(html);
iframeDocument.close();
},
//获取上传控件名称
getInputFileName: function () {
return (new Date()).valueOf();
},
//创建上传控件到创建的iframe中
createInputFile: function () {
var that = this;
var dcmt = this.getIframeContentDocument();
var input = dcmt.createElement("input");
input.type = "file";
input.setAttribute("name", "input" + this.getInputFileName());
input.setAttribute("multiple","true");
input.onchange = function () {
//检查是否为允许上传的文件
if(this.files==undefined){
var fileSuf = this.value.substring(this.value.lastIndexOf(".") + 1);
if (!that.checkFileIsUpload(fileSuf, that.settings.fileSuffixs)) {
dcmt.forms[0].innerHTML = "";
that.settings.onCheckUpload(that.settings.errorText.replace("{0}", fileSuf));
return;
}
}else{
for (var i = 0; i < this.files.length; i++) {
var tempName=this.files[i].name.substring(this.files[i].name.lastIndexOf(".") + 1);
if (!that.checkFileIsUpload(tempName, that.settings.fileSuffixs)) {
dcmt.forms[0].innerHTML = "";//清空上传队列
that.settings.onCheckUpload(that.settings.errorText.replace("{0}", tempName));
return;
}
}
}
//选中后的回调
that.settings.onChosen(this.value, this);
if (that.checkFileIsExist(this.value)) {
//保存已经选择的文件路径
that.choseFilePath.push({ "name": this.name, "value": this.value });
var status = that.settings.onSameFilesHandle(this.value);
if (typeof status === "boolean" && !status) {
that.removeFile(this.value);
return;
}
} else {
//保存已经选择的文件路径
that.choseFilePath.push({ "name": this.name, "value": this.value });
}
if (!that.settings.buttonFeature) {
that.submitUpload();
}
};
dcmt.forms[0].appendChild(input);
return input;
},
//获取创建的iframe中的document对象
getIframeContentDocument: function () {
return this.iframe.contentDocument || this.iframe.contentWindow.document;
},
//获取创建的iframe所在的window对象
getIframeWindow: function () {
return this.iframe.contentWindow || this.iframe.contentDocument.parentWindow;
},
//获取创建的iframe内部iframe的document对象
getInsideIframeContentDocument: function () {
return this.getIframeWindow().getDCMT();
},
//获取上传input控件
getUploadInput: function () {
var inputs = this.getIframeContentDocument().getElementsByTagName("input");
var len = inputs.length;
if (len > 0) {
if (!inputs[len - 1].value) {
return inputs[len - 1];
} else {
return this.createInputFile();
}
}
return this.createInputFile();
},
//forEach迭代函数
forEach: function (/*数组*/arr, /*代理函数*/fn) {
var len = arr.length;
for (var i = 0; i < len; i++) {
var tmp = arr[i];
if (fn.call(tmp, i, tmp) == false) {
break;
}
}
},
//提交上传
submitUpload: function () {
var status = this.settings.onSubmitHandle(this.choseFilePath.length);
if (typeof status === "boolean") {
if (!status) {
return;
}
}
this.clearedNotChooseFile();
var dcmt = this.getIframeContentDocument();
dcmt.forms[0].submit();
},
//检查文件是否可以上传
checkFileIsUpload: function (fileSuf, suffixs) {
var status = false;
this.forEach(suffixs, function (i, n) {
if (fileSuf.toLowerCase() === n.toLowerCase()) {
status = true;
return false;
}
});
return status;
},
//检查上传的文件是否已经存在上传队列中
checkFileIsExist: function (/*当前上传的文件*/file) {
var status = false;
this.forEach(this.choseFilePath, function (i, n) {
if (n.value == file) {
status = true;
return false;
}
});
return status;
},
//清除未选择文件的上传控件
clearedNotChooseFile: function () {
var files = this.getIframeContentDocument().getElementsByTagName("input");
this.forEach(files, function (i, n) {
if (!n.value) {
n.parentNode.removeChild(n);
return false;
}
});
},
//将指定上传的文件从上传队列中删除
removeFile: function (file) {
var that = this;
var files = this.getIframeContentDocument().getElementsByTagName("input");
this.forEach(this.choseFilePath, function (i, n) {
var arr = n.value.split('\\');//注split可以用字符或字符串分割
if (arr[arr.length - 1] == file) {
that.forEach(files, function (j, m) {
if (m.name == n.name) {
m.parentNode.removeChild(m);
return false;
}
});
that.choseFilePath.splice(i, 1);
return false;
}
});
},
//清空上传队列
clearUploadQueue: function () {
this.choseFilePath.length = 0;
this.getIframeContentDocument().forms[0].innerHTML = "";
},
//选择上传文件
chooseFile: function () {
var uploadfile;
if (this.choseFilePath.length == this.settings.maximumFilesUpload) {
if (this.settings.maximumFilesUpload <= 1) {
this.choseFilePath.length = 0;
var files = this.getIframeContentDocument().getElementsByTagName("input");
if (!files.length) {
uploadfile = this.getUploadInput();
$(uploadfile).click();
return;
} else {
uploadfile = files[0];
$(uploadfile).click();
return;
}
} else {
return;
}
}
uploadfile = this.getUploadInput();
$(uploadfile).click();
}
};
引用那个js文件后,
<div class="alertTypeContent">
<table cellpadding="5" cellspacing="5" width="100%">
<tr>
<td width="80">导入:</td>
<td>
<div class="file"><input type="button" name="files" value="浏览..." class="btn-green" id="upload">选择文件</div>
</td>
</tr>
<tr>
<td colspan="2" class="text_center" id="ImportShopText"></td>
</tr>
</table>
</div>
$("#upload").uploadFile({
url: "/VipShopManage/UploadShop", //上传地址
fileSuffixs: ["xls", "xlsx"], //可上传的文件类型
buttonFeature: false, //是否开启自动上传。true为不开启
errorText: "{0}", //错误提示
maximumFilesUpload: , //最大文件上传数
onChosen: function (file, obj) { //选择文件后的回调函数,(file为选中文件的本地路径;obj为当前的上传控件实例)
var msgSpan = $("#ImportShopText");
msgSpan.html("正在验证数据,请稍等......");
},
onComplete:
//上传成功以后执行该方法.注意方法的参数一定和原有的方法的参数保持一致
function(serverData) {
var msgSpan = $("#ImportShopText");
var result = eval('(' + serverData + ')');
) {
msgSpan.html(result.msg);
}
//部分数据不正确
) {
var failTxt = $("#failTxt");
var failShopTxt = $("#failShopTxt");
var txtMsg = "";
$(result.data).each(function(key, value) {
txtMsg += "<li>" + value + "</li>";
});
failTxt.html(result.msg);
failShopTxt.html(txtMsg);
closeImportShop();
openFailShop();
}
) {
closeImportShop();
opensuccess();
$("#successTxt").html(result.msg);
}
return;
}
});
controller:
public ActionResult UploadShop()
{
var res = new ToResponse();
var resultList = new List<string>();
//上传
try
{
; i < Request.Files.Count; i++)
{
var httpPostedFileBase = Request.Files[i];
if (httpPostedFileBase != null)
{
string fileName = Path.GetFileName(httpPostedFileBase.FileName);
string fileEx = System.IO.Path.GetExtension(fileName); //获取上传文件的扩展名
var postedFileBase = Request.Files[i];
var stream = postedFileBase.InputStream;
byte[] bytes = new byte[stream.Length];
stream.Read(bytes, , bytes.Length);
stream.Seek(, SeekOrigin.Begin);
)
{
continue;
}
const string fileType = ".xls,.xlsx"; //定义上传文件的类型字符串
fileName = DateTime.Now.ToString("yyyyMMddhhmmss") + fileEx;
if (fileEx != null && !fileType.Contains(fileEx))
{
res = , msg = "请按正确文件格式(.xls或.xlsx)导入!",data=null};
return Content(JsonConvertTool.SerializeObject(res));
}
string filePath = ConfigurationManager.AppSettings["ImportShopFilePath"];
if (!Directory.Exists(filePath))
{
Directory.CreateDirectory(filePath);
}
string savePath = Path.Combine(filePath, fileName);
var fs = new FileStream(savePath, FileMode.OpenOrCreate, FileAccess.Write);
fs.Write(bytes, , bytes.Length);
fs.Flush();
fs.Close();
//获取excel中的内容
DataTable contactTable = ReadExcelByOledb(savePath, fileEx);
//删除文件
System.IO.File.Delete(savePath);
foreach (DataRow item in contactTable.Rows)
{
)
{
res = , msg = "请按正确文件格式(.xls或.xlsx)导入!", data = null};
return Content(JsonConvertTool.SerializeObject(res));
}
] != null)
{
].ToString();
)
{
val = val.Replace(" ", "");
}
resultList.Add(val);
}
}
)
{
res = , msg = "内容为空,验证失败!", data = null };
return Content(JsonConvertTool.SerializeObject(res));
}
)
{
res = , msg = "导入数据不能大于1000条!", data = null };
return Content(JsonConvertTool.SerializeObject(res));
}
//验证供货商
var noValidateNames = ValidateShop(resultList);
)
{
res = new ToResponse
{
code = -,
msg = "以下内容(" + noValidateNames .Count+ "条)验证未通过,请检查后重新导入:",
data = noValidateNames
};
return Content(JsonConvertTool.SerializeObject(res));
}
)
{
res = new ToResponse
{
code = ,
msg = "导入成功!共导入" + resultList.Count + "条数据!",
data = null
};
return Content(JsonConvertTool.SerializeObject(res));
}
}
}
}
catch (Exception ex)
{
LogHelper.ErrorFormat("UploadShop:导入供货商发生错误:错误信息是{0}", ex);
res = , msg = "导入失败!", data = null };
}
return Content(JsonConvertTool.SerializeObject(res));
}
private DataTable ReadExcelByOledb(string fileNamePath, string fileEx)
{
string connStr = "";
if (fileEx == ".xls")
{
connStr = "Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=Excel 8.0;data source=" + fileNamePath +
"HDR=Yes; IMEX=1";
}
else
{
connStr = "Provider=Microsoft.Ace.OleDb.12.0;Data Source=" + fileNamePath +
";Extended Properties='Excel 12.0; HDR=Yes; IMEX=1'";
}
var oledbconn1 = new OleDbConnection(connStr);
oledbconn1.Open();
DataTable table = oledbconn1.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
)
{
]["TABLE_NAME"].ToString().Trim();
string sql = string.Format("SELECT * FROM [{0}]", strTableName);
table = new DataTable();
OleDbDataAdapter da = new OleDbDataAdapter(sql, oledbconn1);
da.Fill(table);
}
oledbconn1.Close();
return table;
}
}
MVC异步 导入excel文件的更多相关文章
- .Net MVC 导入导出Excel总结(三种导出Excel方法,一种导入Excel方法) 通过MVC控制器导出导入Excel文件(可用于java SSH架构)
.Net MVC 导入导出Excel总结(三种导出Excel方法,一种导入Excel方法) [原文地址] 通过MVC控制器导出导入Excel文件(可用于java SSH架构) public cl ...
- springMVC(5)---导入excel文件数据到数据库
springMVC(5)---导入excel文件数据到数据库 上一篇文章写了从数据库导出数据到excel文件,这篇文章悄悄相反,写的是导入excel文件数据到数据库.上一篇链接:springMVC(4 ...
- POI异步导入Excel兼容xsl和xlsx
项目架构:spring+struts2+hibernate4+oracle 需求:用户导入excel文件,导入到相应的数据表中,要求提供导入模板,支持xls和xlsx文件 思路分析: 1.提供一个下载 ...
- Java POI导入Excel文件
今天在公司需要做个导入Excel文件的功能,所以研究了一下,参考网上的一些资料总算是做出来了,在此记录一下防止以后忘记怎么弄. 本人用的是poi3.8,所以需要的JAR包如下: poi-3.8.jar ...
- phpexcel导入excel文件报the filename xxx is not recognised as an OLE file错误。
工作中频繁会用phpexcel类导入excel文件的数据到数据库,目前常用的excel文件格式有:xls.csv.xlsx. 刚开始,针对xls文件,使用如下程序,能正常运行: $objReader ...
- YII使用PHPExcel导入Excel文件的方法
1.下载phpexcel,将压缩包中的classes复制到protected/extensions下并修改为PHPExcel. 2.修改YII配置文件config/main.php 'import'= ...
- excel数据 入库mysql 和 mysql数据 导入excel文件
1.excel数据入库mysql 首先准备excel文件, 标红的地方需要留意,一个是字段名所在行,一个表名对应页: 然后私用mysql工具 navicat, 选择数据库,然后导入文件, 选中相应ex ...
- java后端导入excel模板和导入excel文件去读数据
模板转载地址:https://www.cnblogs.com/zhangyangtao/p/9802948.html 直接上代码(我是基于ssm写的demo,导入文件目前只能读取.xls后缀的exce ...
- C# Aspose.Cells方式导入Excel文件
读取Excel 类 我返回的是DataTable 类型 也可以返回DataSet类型 public class XlsFileHelper { public DataTable ImportExcel ...
随机推荐
- 怎样在Java中实现基本数据类型与字符之间的转换
摘要:在我们对Java的学习当中数据类型之间的转换,是我们常见的事,我们也都知道基本数据类型之间有自动转换和强制转换,在int . short . long .float .double之间的转 ...
- 【转】Netty那点事(二)Netty中的buffer
[原文]https://github.com/code4craft/netty-learning/blob/master/posts/ch2-buffer.md 上一篇文章我们概要介绍了Netty的原 ...
- 强烈推荐android studio用的几个插件,androidstudio
不懂安装studio插件,看参考博文:android stuido插件安装:http://blog.csdn.net/liang5630/article/details/46372447 1.Butt ...
- 支持向量机(SVM)算法的matlab的实现
支持向量机(SVM)的matlab的实现 支持向量机是一种分类算法之中的一个,matlab中也有对应的函数来对其进行求解:以下贴一个小例子.这个例子来源于我们实际的项目. clc; clear; N= ...
- C++在使用Qt中SLOT宏须要注意的一个小细节
大家都知道C++虚函数的机制,对于基类定义为虚函数的地方,子类假设覆写,在基类指针或者引用来指向子类的时候会实现动态绑定. 但假设指针去调用非虚函数,这个时候会调用C++的静态绑定,去推断当前的指针是 ...
- MySQL和PostgreSQL 导入数据对照
在虚拟机上測评了下MySQL 和 PostgreSQL 的各种LOAD FILE方式以及时间. 由于是虚拟机上的測评,所以时间仅仅做參考,不要太较真, 看看就好了.MySQL 工具: 1. 自带 ...
- android136 360 拖拽
差补器原理: 图标拖拽: activity_drag_view.xml <?xml version="1.0" encoding="utf-8"? ...
- C 二叉树 1
二叉链表: #define _CRT_SECURE_NO_WARNINGS #include <stdlib.h> #include <string.h> #include & ...
- interactive_timeout
[mysqld] interactive_timeout 交互式连接 会话1 [root@localhost ~]# mysql -umysql -p Enter password: Welcome ...
- android中3种实现动画效果的方法
3中实现动画的方法:ImageView imgView = (ImageView)findViewById(R.id.imageView_logo); //第一种动画方法,使用AlphaAnimati ...