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 ...
随机推荐
- iOS 开发 上传代码至github(转)
一.注册github账号 首先需要注册一个github账号,注册地址:https://github.com 接着会来到这 然后会收到一封github发的邮件,进入邮箱验证 二.创建个人的githu ...
- Win7 U盘安装Ubuntu16.04 双系统
Win7系统下安装Ubuntu系统,主要分为三步: 第1步:制作U盘启动盘 第2步:安装Ubuntu系统 第3步:创建启动系统引导 第1步:制作U盘启动盘 1.下载Ubuntu16.04安装镜像,官网 ...
- Linux下JDK安装位置
新手在Linux上安装JDK时,不知道应该将JDK安装在哪比较合适.首先简要了解下Linux中部分目录的作用. /bin---用来贮存用户命令./usr/bin 也被用来贮存用户命令. /sbin- ...
- Mysql 培训
1. Mysql 培训 1.1. 培训目的 本文档是针对MySQL 数据库方面的基础培训,为了使项目组成员能够达到使用MySQL 数据库的目的. 1.2. 培训对象 开发者 1.3. 经常使用词及符 ...
- Android Sqlite 导入CSV文件 .
http://blog.csdn.net/johnnycode/article/details/7413111 今天遇到 Oracle 导出的12万条CSV格式数据导入 Android Sqlite ...
- 定时自动同步文件,支持多文件夹同步,支持过滤文件和文件夹,解决FileSystemWatcher多次文件触发事件(源码)
博客园里面有很多同步工具和软件,关于FileSystemWatcher类解释的也很多,但收集了很多文章后,感觉没好的方法,自己没事写了一个定时文件同步,借鉴了很多博客园朋友的东西: 上主菜: 配置文件 ...
- C#_LINQ(LINQ to Entities)
LINQ to Entities 是 LINQ 中最吸引人的部分.它让你可以使用标准的 C# 对象与数据库的结构和数据打交道.使用 LINQ to Entities 时,LINQ 查询在后台转换为 S ...
- velocity properties
resource.loader=webapp webapp.resource.loader.class=org.apache.velocity.tools.view.servlet.WebappLoa ...
- Lipo Error!! can't open input file
参考文章:http://stackoverflow.com/questions/17348912/lipo-error-cant-open-input-file I got it to Work, i ...
- keyStore vs trustStore--转载
原文:http://lukejin.iteye.com/blog/605634 今天有同事向我问起这两个概念,所以我就记录下.首先我们得澄清一些概念.一个web应用如果需要提供以https的方式访问的 ...