Export to Excel in Blazor

Export Data to Excel file in Blazor using .Net ClosedXML library

October 17, 2020

In this article we will cover how to Export data to Excel file from Blazor Web Assembly Application using .Net ClosedXML library

Let's Start:

Add below mentioned dll as reference from Nuget Package. And add it to blazor code file (using ClosedXML.Excel;)

ClosedXML.dll

Add Download button to .blazor file

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

Add below mentioned code to blazor code file

public async Task DownloadExcelDocument()
{
    string apiUri = "Country";
    List<Countrycountries = await httpClient.GetJsonAsync<List<Country>>(apiUri);
 
    using (var workbook = new XLWorkbook())
    {
        IXLWorksheet worksheet =
        workbook.Worksheets.Add("Countries");
        worksheet.Cell(1, 1).Value = "Title";
        worksheet.Cell(1, 2).Value = "Code";
 
        for (int i = 1; i <= 2; i++)
        {
            worksheet.Cell(1, i).Style.Font.Bold = true;
        }
 
        int index = 1;
        foreach (var country in countries)
        {
            worksheet.Cell(index + 1, 1).Value = country.Country_Title;
            worksheet.Cell(index + 1, 2).Value = country.Country_Code;
 
            index++;
        }
 
        using (var stream = new MemoryStream())
        {
            workbook.SaveAs(stream);
            var content = stream.ToArray();
 
            var fileName = "Countries.xlsx";
            await JSRuntime.InvokeAsync<object>("saveAsFile"fileNameConvert.ToBase64String(content));
        }
    }
}

Post Comments(0)

Leave a reply

Will not be displayed in comment box .

Loading...