【发布时间】:2021-02-08 21:01:16
【问题描述】:
我有获取 FilePath 并将所有 Excel 信息返回到列表中的函数。 我的实际问题不是功能,而是如果我的 FilePath 错误或文件不存在时无法工作的错误系统。
我尝试了一些错误基本捕获,但它不起作用并且我的程序崩溃并显示此消息:
System.NullReferenceException:'对象引用未设置为对象的实例。'
我在这里粘贴我的功能:
public List<ImportExcelModel> GetList(string filePath)
{
List<ImportExcelModel> ExcelList = new List<ImportExcelModel>();
try
{
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
FileInfo fileInfo = new FileInfo(filePath);
using (ExcelPackage excelPackage = new ExcelPackage(fileInfo))
{
ExcelWorksheet worksheet = excelPackage.Workbook.Worksheets.FirstOrDefault();
int totalColumn = worksheet.Dimension.End.Column; // <- Error Message is print here
int totalRow = worksheet.Dimension.End.Row;
for (int row = 2; row <= totalRow; row++)
{
ImportExcelModel ll = new ImportExcelModel();
for (int col = 1; col <= totalColumn; col++)
{
if (col == 1) ll.DPT = worksheet.Cells[row, col].Value == null ? string.Empty : worksheet.Cells[row, col].Value.ToString();
if (col == 2) ll.Description = worksheet.Cells[row, col].Value == null ? string.Empty : worksheet.Cells[row, col].Value.ToString();
if (col == 3) ll.Conditionnement = worksheet.Cells[row, col].Value == null ? string.Empty : worksheet.Cells[row, col].Value.ToString();
if (col == 4) ll.StockInitial = worksheet.Cells[row, col].Value == null ? string.Empty : worksheet.Cells[row, col].Value.ToString();
if (col == 5) ll.Entree = worksheet.Cells[row, col].Value == null ? string.Empty : worksheet.Cells[row, col].Value.ToString();
if (col == 6) ll.Sortie = worksheet.Cells[row, col].Value == null ? string.Empty : worksheet.Cells[row, col].Value.ToString();
if (col == 7) ll.StockMini = worksheet.Cells[row, col].Value == null ? string.Empty : worksheet.Cells[row, col].Value.ToString();
if (col == 8) ll.StockReel = worksheet.Cells[row, col].Value == null ? string.Empty : worksheet.Cells[row, col].Value.ToString();
if (col == 9) ll.Localisation = worksheet.Cells[row, col].Value == null ? string.Empty : worksheet.Cells[row, col].Value.ToString();
}
ExcelList.Add(ll);
}
}
return ExcelList;
}
catch (Exception ex)
{
return ExcelList;
}
}
编辑:是的,如果我无法打开文件,我想要空列表
【问题讨论】:
标签: c# asp.net asp.net-core blazor