asp.net-coreblazorblazor-server-sideasp.net-blazor

How to upload and read an excel file (.xlsx) in a blazor server project


I have a blazor server project and I need to send an excel file with data to create objects of an entity. I have searched a lot and have not found anything that has worked for me. I believe my problem is accessing the file to then be able to do what I want.

In my blazor component i have:

<InputFile OnChange="@ImportExcelFile" accept=".xlsx" multiple="false"></InputFile>
@code {
    async Task ImportExcelFile(InputFileChangeEventArgs e)
    {
        await EnrollmentService.CreateEnrollmentByExcel(e);
    }
}

In my EnrollmentService.cs i need to read file.

If anyone can help me I would be very grateful.


Solution

  • I can already access my entered file, I was researching and found several ways but it didn't satisfy my requirements because they were trying to store the file in a folder, I just wanted to read the data and store it in memory, and I got this that helped me. Thanks.

    async Task ImportExcelFile(InputFileChangeEventArgs e)
    {
        foreach (var file in e.GetMultipleFiles(1))
        {
            try
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    // copy data from file to memory stream
                    await file.OpenReadStream().CopyToAsync(ms);
                    // positions the cursor at the beginning of the memory stream
                    ms.Position = 0;
    
                    // create ExcelPackage from memory stream
                    ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
                    using (ExcelPackage package = new ExcelPackage(ms))
                    {
                        ExcelWorksheet ws = package.Workbook.Worksheets.FirstOrDefault();
                        int colCount = ws.Dimension.End.Column;
                        int rowCount = ws.Dimension.End.Row;
                        var s = ws.Cells[2, 2].Value;
                        // rest of the code here...
                    }
                }
            }
            catch (Exception ex)
            {
                throw;
            }
        }
    }