【发布时间】:2018-07-16 13:24:20
【问题描述】:
在我的索引视图中,我编写了以下代码:
@using (Html.BeginForm("Import", "ItemDetails", FormMethod.Post, new {
enctype="multipart/form-data"}))
{
@Html.Raw(ViewBag.Error);
<span>import from Excel :</span>
<input type="file" /> <input type="submit" value="import" class="btn btn-
primary">
}
所以我上传了一个excel文件并按下导入按钮,问题是代码看不到excel文件,它看到excel文件为空,虽然我已经上传了扩展名xlsx
public ActionResult Import(HttpPostedFileBase excelFile)
{
if (excelFile == null || excelFile.ContentLength == 0 )
{
ViewBag.Error = "select excel file <br/>";
return View("Index");
}
else
{
//if file is not null
if (excelFile.FileName.EndsWith("xls") ||
excelFile.FileName.EndsWith("xlsx"))
{
string path = Server.MapPath("~/Content" +
excelFile.FileName);
if (System.IO.File.Exists(path))
{
System.IO.File.Delete(path);
}
excelFile.SaveAs(path);
Excel.Application application = new Excel.Application();
Excel.Workbook workBook =
application.Workbooks.Open(path);
Excel.Worksheet worksheet = workBook.ActiveSheet;
Excel.Range range = worksheet.UsedRange;
List<ItemDetails> itemDetails = new List<ItemDetails>();
for (int x = 1; x < range.Rows.Count; x++)
{
ItemDetails i = new ItemDetails();
i.Id = ((Excel.Range)range.Cells[x, 1]).Text;
i.Factory = ((Excel.Range)range.Cells[x, 2]).Text;
i.ItemCode = ((Excel.Range)range.Cells[x, 3]).Text;
i.Description = ((Excel.Range)range.Cells[x,4]).Text;
i.UnitMeasure = ((Excel.Range)range.Cells[x,5]).Text;
i.Weight = ((Excel.Range)range.Cells[x, 6]).Text;
itemDetails.Add(i);
}
ViewBag.itemDetails = itemDetails;
return View("Success");
}
else
{
ViewBag.Error = "the file type is not correct<br/>";
return View("Index");
}
}
}
【问题讨论】:
标签: .net excel file model-view-controller import