我有一个函数,它获取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;
}
}
编辑:是的,如果我不能打开文件,我想要空列表
System.IO.File.Exists(路径(将返回true/false。使用此项可查明文件是否存在