Step 7 .Controller
7-1先using
using ithome2.Models;
7-2建立上傳頁面 UploadExcel() 以及儲存結果頁面 SaveExcel()
public ActionResult UploadExcel()
{
return View();
}
[AcceptVerbs(HttpVerbs.Post)]
[HttpPost]
public ActionResult SaveExcel(HttpPostedFileBase upfile)
{
string savePath = @"F:\ttt\"; //儲存的檔案路徑
if (upfile == null)
{
ViewBag.fal = "請選擇檔案上傳";
return View();
}
string fileName = System.IO.Path.Combine(savePath + upfile.FileName);
// string savePath = @"C:\Program Files\IIS Express\";
//存Excel
if (upfile != null)
{
if (upfile.ContentLength > 0)
{
string saveFile = System.IO.Path.Combine(savePath + upfile.FileName);
ViewBag.save = saveFile;
upfile.SaveAs(saveFile);
}
var excelFile = new LinqToExcel.ExcelQueryFactory(fileName);
var excel = excelFile.Worksheet<exl>("工作表1"); //取得工作區欄位名稱
foreach (var item in excel) //item 為excel欄位的值
{
var data = new ExcelModel();
if (item.name != null)
{
data.name = item.name;
}
else
{
data.name = "";
}
if (item.tel != null)
{
data.tel = item.tel;
}
else
{
data.tel = "";
}
ViewBag.Msg = "";
if (item.tel.Length != 10)
{
ViewBag.Msg += "上傳失敗:" + item.tel + " 錯誤原因:此筆【電話號碼】錯誤(應為10碼數字)<br />";
}
else
{
Save_Excel(data.name.Trim(), data.tel.Trim());
ViewBag.Msg += "資料成功建立:" + item.name + "_" + item.tel + "<br>";
}
}
return View();
}
else
{
ViewBag.Msg += "檔案上傳失敗";
return View();
}
}
public class exl
{
public string name { get; set; }
public string tel { get; set; }
}
Step 8 .View()
8-1 UploadExcel()
@{
ViewBag.Title = "檔案批次匯入";
}
<h2>Excel檔案批次匯入</h2>
@using (Html.BeginForm("SaveExcel", "Excel", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="upfile" />
<input type="submit" name="upload" value="上傳" />
}
<br>
8-2 SaveExcel
@{
ViewBag.Title = "上傳Excel結果";
}
<h2>上傳Excel結果</h2>
<font color="red"> @Html.Raw(ViewBag.Msg) </font>
9.上傳時 錯誤訊息
解決方案 下載套件:
https://www.microsoft.com/zh-tw/download/details.aspx?id=13255
建立Excel 資料
11.儲存結果(1筆成功寫入,1筆電話為4碼,錯誤不寫入)
由於明天是難得的假日,所以文章內容可能會沒這個多圖片以及程式碼~
參考網址:https://dotblogs.com.tw/dragoncancer/2016/03/31/102924