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));
            }

        }

    }
  }
Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.