我正在尝试使用EPPlus上传Excel文件。我不认为我的excel文件为空,但其中包含内容。
我收到此错误: worksheet.Dimension.Rows ='worksheet.Dimension.Rows'引发了类型为'System.NullReferenceException'的异常
在此行上:int rowCount = worksheet.Dimension.Rows;
[HttpPost("Excel")]
public string UploadExcel(IFormFile file)
{
var filePath = Path.GetTempFileName();
FileInfo excel = new FileInfo(filePath);
using (ExcelPackage package = new ExcelPackage(excel))
{
StringBuilder sb = new StringBuilder();
ExcelWorksheet worksheet = package.Workbook.Worksheets[file.FileName];
int rowCount = worksheet.Dimension.Rows;
int ColCount = worksheet.Dimension.Columns;
bool bHeaderRow = true;
for (int row = 1; row <= rowCount; row++)
{
for (int col = 1; col <= ColCount; col++)
{
if (bHeaderRow)
{
sb.Append(worksheet.Cells[row, col].Value.ToString() + "\t");
}
else
{
sb.Append(worksheet.Cells[row, col].Value.ToString() + "\t");
}
}
sb.Append(Environment.NewLine);
}
return sb.ToString();
}
答案 0 :(得分:2)
您可以验证是否正在加载工作台吗?
//examine in the debugger to make sure the worksheet you want is loaded
var worksheets = package.Workbook.Worksheets.ToList();
如果这不起作用,您可以尝试其中之一吗?
var worksheet = package.Workbook.Worksheets[0];
var worksheetFirst = package.Workbook.Worksheets.First();
更新:
真正的错误是您尝试使用var filePath = Path.GetTempFileName();
读取临时文件。您需要阅读实际的Excel文件。例如,您可以使用Path.GetFullPath("path/to/the/excel/file.xls");