在索引视图中,我编写以下代码:
@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文件,尽管我已经用扩展名xlsx上传了该文件,但它却认为excel文件为空
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");
}
}
}
答案 0 :(得分:0)
您需要将发布的文件连接到变量:
<input type="file" name="excelFile" />