Articles in this section
Category / Section

How to Export data to Excel in Blazor?

5 mins read

Syncfusion Excel (XlsIO) library is a .NET Excel library used to create, read, and edit Excel documents. Also, converts Excel documents to PDF files. This article explains how to export data from a data table to Excel in Blazor platform using XlsIO.

Steps to export data to Excel in Blazor:

Step 1: Create a new C# Blazor Server-side application project. Select Blazor App from the template and click the Next button.

Create Blazor Server Side application in Visual Studio

Create Blazor Server-side application in Visual Studio

Step 2: Now, the project configuration window will popup. Click Create button to create a new project with the required project name.

Name the project

Name the project

Step 3: Choose Blazor Server App and click Create button to create a new Blazor Server-Side application

Create Blazor Server Side application in Visual Studio

Select Blazor App

Step 4: Install the Syncfusion.XlsIO.Net.Core NuGet package as reference to your Blazor application from the NuGet.org.

Install NuGet package to the project

Install NuGet package to the project

Step 5: Create a razor file with name as Excel under Pages folder and include the following namespaces in the file.

C#

@page "/Excel"
@using System.IO;
@using ServerSideApplication;
@inject ServerSideApplication.Data.ExcelService service
@inject Microsoft.JSInterop.IJSRuntime JS

 

Step 6: Add the following code to create a new button.

CSHTML

<h2>Syncfusion Excel library (Essential XlsIO)</h2>
<p>Syncfusion Excel library (Essential XlsIO)  is a Blazor Excel library used to create, read, edit, and convert Excel files in your applications without Microsoft Office dependencies.</p>
<button class="btn btn-primary" @onclick="@CreateDocument">Create Document</button>

 

Step 7: Add the following code in Excel.razor file to create and download the Excel document.

C#

@code {
    MemoryStream excelStream;
 
    /// <summary>
    /// Create and download the Excel document
    /// </summary>
    protected async void CreateDocument()
    {
        excelStream = service.CreateExcel();
        await JS.SaveAs("Sample.xlsx", excelStream.ToArray());
    }
}

 

Step 8: Create a new cs file with name as ExcelService under Data folder and include the following namespaces in the file.

C#

using Syncfusion.XlsIO;
using System.IO;
using System.Data;

 

Step 9: Create a new MemoryStream method with name as CreateExcel and include the following code snippet to export data to Excel document in Blazor Server-Side application.

C#

//Create an instance of ExcelEngine
using (ExcelEngine excelEngine = new ExcelEngine())
{
    IApplication application = excelEngine.Excel;
    application.DefaultVersion = ExcelVersion.Excel2016;
 
    //Create a workbook
    IWorkbook workbook = application.Workbooks.Create(1);
    IWorksheet worksheet = workbook.Worksheets[0];
 
    //Initialize DataTable and data get from SampleDataTable method
    DataTable table = SampleDataTable();
 
    //Import data from DataTable
    worksheet.ImportDataTable(table, true, 1, 1, true);
 
    //Save the document as a stream and retrun the stream.
    using (MemoryStream stream = new MemoryStream())
    {
        //Save the created Excel document to MemoryStream
        workbook.SaveAs(stream);
        return stream;
    }
}

 

Step 10: Include the following code snippet for SampleDataTable method.

C#

private DataTable SampleDataTable()
{
    //Here we create three columns
    DataTable table = new DataTable();
    table.Columns.Add("ID", typeof(int));
    table.Columns.Add("Item", typeof(string));
    table.Columns.Add("Name", typeof(string));
 
    //Here we add four DataRows
    table.Rows.Add(1, "Soap", "David");
    table.Rows.Add(2, "Paste", "Sam");
    table.Rows.Add(3, "Cream", "Christoff");
    table.Rows.Add(4, "Powder", "Janet");
 
    return table;
}

 

Step 11: Create a new class file in the project, with name as FileUtils and add the following code to invoke the JavaScript action for downloading the file in browser.

C#

public static class FileUtils
{
    public static ValueTask<object> SaveAs(this IJSRuntime js, string filename, byte[] data)
        => js.InvokeAsync<object>(
           "saveAsFile",
           filename,
           Convert.ToBase64String(data));
}

 

Step 12: Add the following JavaScript function in the _Host.cshtml file present under Pages folder.

C#

<script type="text/javascript">
    function saveAsFile(filename, bytesBase64) {
 
    if (navigator.msSaveBlob) 
 {
        //Download document in Edge browser
        var data = window.atob(bytesBase64);
        var bytes = new Uint8Array(data.length);
        for (var i = 0; i < data.length; i++) 
  {
            bytes[i] = data.charCodeAt(i);
        }
        var blob = new Blob([bytes.buffer], { type: "application/octet-stream" });
        navigator.msSaveBlob(blob, filename);
    }
    else 
 {
        var link = document.createElement('a');
        link.download = filename;
        link.href = "data:application/octet-stream;base64," + bytesBase64;
        document.body.appendChild(link); // Needed for Firefox
        link.click();
        document.body.removeChild(link);
    }
}
</script>

 

A complete working example for exporting data to Excel document in Blazor, can be downloaded from  Export-data-to-Excel-in-Blazor.zip.

By executing the program, you will get the Excel file as below.

Output Excel document

Output Excel document

Take a moment to peruse the documentation, where you can find basic worksheet data manipulation options along with features like Conditional Formatting, worksheet calculations through Formulas, adding Charts in worksheet or workbook, organizing and analyzing data through Tables and Pivot Tables, appending multiple records to worksheet using Template Markers, and most importantly PDF and Image conversions etc. with code examples.

Click here to explore the rich set of Syncfusion Excel (XlsIO) library features.

Note:

Starting with v16.2.0.x, if you reference Syncfusion assemblies from trial setup or from the NuGet feed, include a license key in your projects. Refer the link to learn about generating and registering Syncfusion license key in your application to use the components without trail message.

 

 

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please sign in to leave a comment