一:view部分
<form method="post" enctype="multipart/form-data" action="/Position/ImportExcel" class="form-group">
<input name="file" type="file" id="file" />
<button id="btn_import" type="submit" class="btn btn-info">
<span class="glyphicon glyphicon-pencil"></span>导入
</button>
</form>
1.注意表单部门必须加 enctype = "multipart/form-data" ,否则后台File.ContentLength 为0;
二:controller部门
public ActionResult ImportExcel()
{
HttpPostedFileBase File = Request.Files["file"];
string content = "";
if (File.ContentLength>0)
{
var Isxls = System.IO.Path.GetExtension(File.FileName).ToString().ToLower();
if (Isxls != ".xls" && Isxls != ".xlsx")
{
Content("请上传Excel文件");
}
var FileName = File.FileName;//获取文件夹名称
var path = Server.MapPath("~/FileExcel/" + FileName);
File.SaveAs(path);//将文件保存到服务器
PositionBLL bll = new PositionBLL();
var list = bll.FileUpLoad(path);
if (list.Count>0)
{
int num = bll.LoadFile(list);
if (num>0)
{
content = "<script>alert('数据导入成功'),window.location.href='/Position/Index'</script>";
}
}
else
{
content = "<script>alert('导入的数据不能为空'),window.location.href='/Position/Index'</script>";
}
}
else
{
content = "<script>alert('请选择上传的文件'),window.location.href='/Position/Index'</script>";
}
return Content(content);
}