首页 > 解决方案 > 导入 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");
                }
            }
        }

标签: .netexcelfilemodel-view-controllernullreferenceexception

解决方案


if (excelFile.ContentLength == 0 || excelFile == null)

需要是

if (excelFile == null || excelFile.ContentLength == 0)

因此,ContentLength如果第一个条件已经是,则不会评估该属性true


推荐阅读