ASP.NET MVC 匯入Excel檔案

落花香殘發表於2018-08-07

一: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);
}

 

相關文章