简体   繁体   中英

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

I am trying to read Excel file in C# .net core 2.2. For reading Excel I am using EpPlus . I have taken reference from File uploads in ASP.NET Core . I have Api like this

 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

        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.

Exception message:

InvalidDataException: The file is not an valid Package file. 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. Trying to read this Excel file:

在此输入图像描述

My question is where am I going wrong?

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

memoryStream.Position = 0;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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