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<Country> countries = 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", fileName, Convert.ToBase64String(content)); } } }
Post Comments(0)