前臺代碼:
<div>
@using (Html.BeginForm("UploadOrderExcel", "Image", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" id="file1" name="file1" />
<input type="submit" name="Upload" value="上傳" />
}
</div>
controller代碼:
public ActionResult UploadWibllExcel()
{
ReturnJson ReJson = new ReturnJson();
try
{
string FileName = DateTime.Now.ToString("yyyyMMddHHmmssfff");
HttpPostedFileBase file = Request.Files["file2"];//獲取目標Excel
string Url = Server.MapPath("~/");
string filetype = file.FileName.Substring(file.FileName.LastIndexOf("."));
file.SaveAs(Url + "/UploadFiles/" + FileName + filetype);
string Path = Url + "/UploadFiles/" + FileName + filetype;
Tools tools = new Tools();//自己定義的類
tools.WibllFormE(Path);
Response.Write("<script>alert('上傳成功')</script>");
}
catch (Exception ex)
{
Response.Write("<script>alert('上傳失敗')</script>");
throw;
}
return null;
}
Tool.cs
public void WibllFormE(string FilePath)
{
DataTable excelDT = null;
ExcelHelper excelhelper = new ExcelHelper(FilePath);
excelDT = excelhelper.ExcelToDataTable("", true);
string PersonInCharge = null;
foreach (DataRow excelDR in excelDT.Rows)
{
PT_Waybill Mod = new PT_Waybill();//定義一個model
Mod.Name= (string)excelDR["負責人"];//excelDR內爲Excel列名
Mod.Describe = (string)excelDR["描述"];
Mod.Type = (string)excelDR["貨物類型"];
Mod.CargoCode = (string)excelDR["訂單號"];
Mod.OrderNumber= (string)excelDR["運單號"];
Mod.WaybillState = Convert.ToInt32((string)excelDR["運單狀態"]);
Mod.GPName = (string)excelDR["省(發貨)"];
Mod.GCName = (string)excelDR["市(發貨)"];
GAName = (string)excelDR["縣區(發貨)"];
Mod.GoodsAddress = (string)excelDR["詳細地址(發貨)"];
Mod.GoodContact = (string)excelDR["聯繫方式(發貨)"];
Mod.GoodUserName = (string)excelDR["聯繫人(發貨)"];
Mod.EndTime = DateTime.FromOADate(Convert.ToDouble((string)excelDR["運單開始時間"]));
Mod.AddTime = DateTime.FromOADate(Convert.ToDouble((string)excelDR["運單結束時間"]));
WaybillService.Insert(Mod);
}
}
ExcelToDateTable爲ExcelDBhelper下的方法,在我上一篇博客裏有。 上傳時間出錯問題:將Excel內的時間格式轉換2018/1/1,然後單元格格式變爲文本格式,在使用上面代碼的DateTime.FromOADate()就行了。