最近在库房项目中加入了批量导入功能,实现过程中有些挫折。下面分享一下需要注意的地方。(代码来源为刘子腾同学)
实现代码:
View:
除了引用基本jquery和EasyUI外,添加一个关于表单的js文件jquery-form.js
<form id="testform" enctype="multipart/form-data" > @*必须加enctype属性 *@
<input id="FileUpload" class="easyui-filebox" name="files" data-options="prompt:'选择文件....'" /> @*必须有name属性*@
<a id="addExcel" class="easyui-linkbutton" data-options="iconCls:'icon-add'" onclick="importExcelTest()">上传</a>
</form>
JS:
function importExcelTest() {
var file = $('#FileUpload').filebox("getText");
//判断文件上传是否为空
if (file == null || file == "") {
$.messager.alert('系统提示', '请选择将要上传的文件!');
return;
}
//分割文件的类型
var file_typename = file.substring(file.lastIndexOf('.'), file.length);
if (file_typename == '.xlsx' || file_typename == 'xls') {
var options = {
method: 'POST',
url: '/WarehousingLog/PostExcel',
data: file,
dataType: 'text',
success: function (data) {
if (data == 'True') {
$.messager.show({
title: '提示',
msg: '用户批量导入成功',
showType: 'slide'
})
$('#FileUpload').filebox("setText", "");
} else {
//$.messager.alert('警告', '导入异常,请检查是否正确使用模板!')
$.messager.alert('提示', data)
}
}
}
$('#testform').ajaxSubmit(options);
} else {
$.messager.alert('提示', '请选择正确的文件类型')
}
}
Controller:
public string PostExcel()
{
HttpPostedFileBase file = Request.Files["files"];//这里的files要与input控件的name属性对应
string strFileName;
string strSavaPath;
string ClientPath = AppDomain.CurrentDomain.BaseDirectory + "ExcelFile\\";//要在Controller同级目录下新建一个ExcelFile文件夹
string strPaperId = "Sheet1";
if (file == null || file.ContentLength <= 0)
{
ViewBag.error = "文件不能为空";
}
strFileName = Path.GetFileName(file.FileName);
int intFilesize = file.ContentLength;
string strNoFilename = System.IO.Path.GetFileNameWithoutExtension(strFileName);
strSavaPath = Path.Combine(ClientPath, strFileName);
file.SaveAs(strSavaPath);
//下面为读取Excel文件
WarehousingLogBLL userbll = new WarehousingLogBLL();
string tablename = "t_user";
List<t_user> listUser = new List<t_user>();
//读取Excel,把数据转换为list
listUser = userbll.ExcelToDataTable(strSavaPath, strPaperId, tablename);
List<t_user> listUserEnd = new List<t_user>(); //最终要添加的数据集合
for (int i = 0; i < listUser.Count; i++)
{
t_user allUser = new t_user();
allUser.userName = listUser[i].userName;
allUser.tel = listUser[i].tel;
allUser.mail = listUser[i].mail;
allUser.remark = listUser[i].remark;
listUserEnd.Add(allUser);
}
bool flag=iwarehousinglogbll.addUserlist(listUserEnd);//添加用户
return "True";
}