.net - 导入 excel 文件 mcv 代码时发生 NullReferenceException
问题描述
我在导入方法的开头放置了一个断点,即使我导入了一个 excel 文件,代码也总是进入第一个条件,这会导致异常,异常说 TestImportFromExcel.dll 中发生了“System.NullReferenceException”类型的异常但未在用户代码中处理
附加信息:对象引用未设置为对象的实例。
public ActionResult Import(HttpPostedFileBase excelFile)
{
if (excelFile.ContentLength == 0 || excelFile == null)
{
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");
}
}
}
解决方案
if (excelFile.ContentLength == 0 || excelFile == null)
需要是
if (excelFile == null || excelFile.ContentLength == 0)
因此,ContentLength
如果第一个条件已经是,则不会评估该属性true
。
推荐阅读
- c# - 可以避免分配 out 值吗?
- python - pyplot.scatter(c='red')。无效的语法?
- css - 颜色荧光笔不适用于 Sublime Text 3 Win 10
- ios - Sharing two image and two text in UIActivityViewController is not working properlly
- php - Laravel Page is not working on Image upload
- powerbi - How to show dates on axis in Stacked Bar chart in Power BI?
- c# - PdfSharpCore image rendering issue
- mysql - 哪个 AWS 产品适用于 Spring MVC 移动应用程序后端?
- jquery - 在 foreach 循环中使用时,Jquery 代码仅对第一个元素起作用
- python - for循环运行时间内的if语句