读取 xlsx EPPlus 核心时出现 NullReference 错误
NullReference Error while reading xlsx EPPlus Core
我正在尝试使用 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();
}
您能否确认正在加载工作集?
//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");
我正在尝试使用 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();
}
您能否确认正在加载工作集?
//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");