How to export data to Excel in Blazor Server.


Currently for one of my Blazor Project, there was requirement to export data to Excel, Initially we use interop, But while hosting on IIS, This approach was not working.

Then we found out one of best open source nuget package manager i.e. ClosedXml . It is very fast and stable nuget package manger.

Step 1: Create the Blazor Server application

Step 2: Create the JS folder write the code for herperlink download as given below

window.saveAsFile = function (fileName, byteBase64) {
    var link = this.document.createElement('a');
    link.download = fileName;
    link.href = "data:application/octet-stream;base64," + byteBase64;
    this.document.body.appendChild(link);
    link.click();
    this.document.body.removeChild(link);
}

Step 3: Write the code for exporting data to excel using ClosedXml like this

@page "/"
@using ClosedXML.Excel
@inject IJSRuntime JSRuntime

<button type="button" @onclick="@(() => DownloadExcelDocument())">Download</button>

@code
{
    public async Task DownloadExcelDocument()
    {
        using (var workbook = new XLWorkbook())
        {
            IXLWorksheet worksheet =
            workbook.Worksheets.Add("Countries");
            worksheet.Cell(1, 1).Value = "Id";
            worksheet.Cell(2, 1).Value = "1";

            using (var stream = new MemoryStream())
            {
                workbook.SaveAs(stream);
                var content = stream.ToArray();
                var fileName = "Countries.xlsx";
                await JSRuntime.InvokeAsync<object>("saveAsFile", fileName, Convert.ToBase64String(content));
            }

        }

    }
  }