我正在尝试在C#dot net core 2.2
中读取Excel文件。为了阅读excel,我使用了EpPlus。我已经从File uploads in ASP.NET Core获得了参考。我有这样的Api
public async Task<ActionResult<ReappropiationAccountViewModel>> Post(IFormFile file)
{
return Ok(await Mediator.Send(new SaveReappropriationAccountCommand { ReappropiationAccountFile = file }));
}
我的命令就是这样
public class SaveReappropriationAccountCommand : IRequest<ReappropiationAccountViewModel>
{
public IFormFile ReappropiationAccountFile { get; set; }
}
在我的处理程序中,我试图像这样阅读excel
using (var memoryStream = new MemoryStream())
{
await request.ReappropiationAccountFile.CopyToAsync(memoryStream);
using (ExcelPackage package = new ExcelPackage(memoryStream))
{
ExcelWorksheet worksheet = package.Workbook.Worksheets[0];
int rowCount = worksheet.Dimension.End.Row;
int colCount = worksheet.Dimension.End.Column;
for (int row = 1; row <= rowCount; row++)
{
for (int col = 1; col <= colCount; col++)
{
var rowValue = worksheet.Cells[row, col].Value;
}
}
}
}
但是我无法读取上载的excel,因为它在InvalidDataException
行中抛出了using (ExcelPackage package = new ExcelPackage(memoryStream))
。
异常消息InvalidDataException: The file is not an valid Package file. If the file is encrypted, please supply the password in the constructor.
一切似乎都是正确的,但无法读取excel数据。 Tryig读取此Excel文件
我的问题是我在哪里做错了?任何建议和解决方案都非常感谢。
答案 0 :(得分:0)
您需要在写完内存流并将其传递给ExcelPackage之前将其设置回开头:
memoryStream.Position = 0;