简体   繁体   English

如何在C#中读取Excel(.XLS和.XLSX)文件?

[英]How to read Excel (.XLS and .XLSX) file in C#?

I am trying to read Excel file in C# .net core 2.2. 我试图在C#.net core 2.2中读取Excel文件。 For reading Excel I am using EpPlus . 为了阅读Excel,我使用的是EpPlus I have taken reference from File uploads in ASP.NET Core . 我从ASP.NET Core中的文件上传中获取了参考。 I have Api like this 我有这样的Api

 public async Task<ActionResult<ReappropiationAccountViewModel>> Post(IFormFile file)
 {
        return Ok(await Mediator.Send(new SaveReappropriationAccountCommand { ReappropiationAccountFile = file }));
 }

And my command is like this 我的命令是这样的

public class SaveReappropriationAccountCommand : IRequest<ReappropiationAccountViewModel>
{
    public IFormFile ReappropiationAccountFile { get; set; }
}

And in my handler I am trying to read Excel like this 在我的处理程序中,我试图像这样阅读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;
                    }
                }

            }
        }

But I am not been able to read the uploaded Excel as it throws InvalidDataException in using (ExcelPackage package = new ExcelPackage(memoryStream)) line. 但是我无法读取上传的Excel,因为它在using (ExcelPackage package = new ExcelPackage(memoryStream))行时抛出InvalidDataException

Exception message: 异常消息:

InvalidDataException: The file is not an valid Package file. InvalidDataException:该文件不是有效的包文件。 If the file is encrypted, please supply the password in the constructor. 如果文件已加密,请在构造函数中提供密码。

Everything seems absolutely right but not been able to read the Excel data. 一切似乎绝对正确,但无法读取Excel数据。 Trying to read this Excel file: 尝试阅读此Excel文件:

在此输入图像描述

My question is where am I going wrong? 我的问题是我哪里出错了?

您需要在写入内存流之后将内存流设置回开头,然后再将其传递给ExcelPackage以进行读取:

memoryStream.Position = 0;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM