Creating a new ExcelPackage using Stream from IFormFile not working

Viewed 2443

I am trying to create an ExcelPackage using EPPlus by uploading an IFormFile. It sounds really simple and all the samples I find are doing what I am doing, but mine doesn't seem to work.

I am using .NET Core and I've verified that the file exists and that it is creating the stream correctly. I was using ClosedXml with the same file and it created the XLWorksheet correct so I know the stream is correct. The issue is when I try to set the worksheet in the below code, the package.Workbook.Worksheets contains zero entries. In other words, package.Workbook.Worksheets.Count = 0. Would someone be able to tell me what I'm missing? Like I said, I've been all over the internet and everyone says this should work, but it doesn't seem to work for me.

Thanks

[HttpPost("Excel"]
public IActionResult UploadExcel([FromForm]IFormFile file)
{
    var stream = file.OpenReadStream();
    using (ExcelPackage package = new ExcelPackage(stream))
    {
        var worksheet = package.Workbook.Worksheets[0];
    }
}

I would expect package.Workbook.Worksheets to contain 1 worksheet with the data from the excel file that is passed in. I don't receive any errors, there is just no worksheet.

1 Answers

I was having the same issue but fixed it by replacing [0] with FirstOrDefault() instead. Also, not sure if it matters, but I used MemoryStream in my sample. Hopefully, this helps anyone who comes across this ticket:

[HttpPost]
public async Task<IActionResult> UploadFile([FromForm] IFormFile file, CancellationToken cancellationToken)
{
    if (file == null || file.Length <= 0)
        return BadRequest("File is empty");

    if (!Path.GetExtension(file.FileName).Equals(".xlsx", StringComparison.OrdinalIgnoreCase))
        return BadRequest("File extension is not supported");

    using (var stream = new MemoryStream())
    {
        await file.CopyToAsync(stream, cancellationToken);
        using (var package = new ExcelPackage(stream))
        {
            ExcelWorksheet worksheet = package.Workbook.Worksheets.FirstOrDefault();
            var rowCount = worksheet.Dimension.Rows;
        }
    }

    return Ok($"{file.FileName} Uploaded");
}
Related