How to Easily Export Data to Excel Files in Blazor
Tags: blazor, csharp, dotnet, webdev
Published: 2021-03-16 12:41:58

---
title: How to Easily Export Data to Excel Files in Blazor
published: true
date: 2021-03-16 11:00:30 UTC
tags: blazor, csharp, dotnet, webdev
canonical_url: https://www.syncfusion.com/blogs/post/export-data-to-excel-in-blazor.aspx
cover_image: https://www.syncfusion.com/blogs/wp-content/uploads/2021/03/Easily-Export-Data-to-Excel-Files-in-Blazor-672x372.png
---

Syncfusion XlsIO  is a [.NET Excel library](https://www.syncfusion.com/excel-framework/net "Link to the Syncfusion .NET Excel Library") which can create, read, and edit Excel files. It can easily convert a [Excel](https://en.wikipedia.org/wiki/Microsoft_Excel "Link to Microsoft Excel Wikipedia page") file into [PDF](https://en.wikipedia.org/wiki/PDF "Link to PDF Wikipedia page"), [HTML](https://en.wikipedia.org/wiki/HTML "Link to HTML Wikipedia page"), images and more file formats. You can also use the Excel library in [WinForms](https://www.syncfusion.com/excel-framework/net "Link to WinForms Excel Library"), [WPF](https://www.syncfusion.com/excel-framework/net "Link to WPF Excel Library"), [UWP](https://www.syncfusion.com/excel-framework/uwp "Link to UWP Excel Library"), ASP.NET ([Web Forms](https://www.syncfusion.com/excel-framework/net "Link to ASP.NET Web Forms Excel Library"),  [MVC](https://www.syncfusion.com/excel-framework/net "Link to ASP.NET MVC Excel Library"), [Core](https://www.syncfusion.com/excel-framework/net-core "Link to ASP.NET Core Excel Library")), [Xamarin](https://www.syncfusion.com/excel-framework/xamarin "Link to Xamarin Excel Library"), [Blazor](https://www.syncfusion.com/excel-framework/blazor "Link to Blazor Excel Library"), [Flutter](https://www.syncfusion.com/flutter-widgets/excel-library "Link to Flutter Excel Library") applications. In this blog, we are going to see how to create an Excel file, export data from a data table to a worksheet, and download the output Excel file in the Blazor platform.

## Generate and download Excel files in Blazor

There are two types of applications in the Blazor platform,  server-side and client-side. In this blog post, we will cover Excel file generation in both. We will:

1. Create a server-side/client-side application.
2. Install XlsIO NuGet package.
3. Add necessary code.
4. Run the application.
5. Download the output Excel document.

**Note: ** If you are new to using our Excel library,  please follow the instructions in our [Getting Started guide](https://help.syncfusion.com/file-formats/xlsio/getting-started "Link to getting started documentation of Syncfusion Excel Library").

## Server-side application

### Create a server-side application

Open **Visual Studio 2019** and choose **Create a new project**.  A dialog will appear. Choose **Blazor App** from the list and click  **Next**.

_![Choose the Blazor App option from the list and click on the Next Button](https://www.syncfusion.com/blogs/wp-content/uploads/2021/03/Choose-the-Blazor-App-option-from-the-list.png)_Choose the **Blazor Server App**  from the list and select the **configure for HTTPS** check box in the **Advanced** section. Then, click   **Create** to create a new Blazor server-side application project. ![Select Blazor Server App](https://www.syncfusion.com/blogs/wp-content/uploads/2021/03/Select-Blazor-Server-App-1.png)

### Install the XlsIO NuGet package

Right- click on the project and select **Manage NuGet Packages**. Navigate to the **Browse** tab, and install the [Syncfusion.XlsIO.Net.Core NuGet](https://www.nuget.org/packages/Syncfusion.XlsIO.Net.Core "Link to install the Syncfusion.XlsIO.Net.Core NuGet package") package as a reference in your Blazor application from [NuGet.org](https://www.nuget.org/ "Link to the NuGet Gallery"). To learn more, refer to [NuGet Package required](https://help.syncfusion.com/file-formats/xlsio/nuget-packages-required "Link to the required NuGet packages documentation") documentation.  
 ![Install the Syncfusion.XlsIO.Net.Core NuGet package to the project](https://www.syncfusion.com/blogs/wp-content/uploads/2021/03/Install-the-Syncfusion.XlsIO_.Net_.Core-NuGet-package-to-the-project.png)

### Add necessary code to server-side application

**Step 1:** Create a Razor file with the name **Excel**  in the **Pages** folder and include the following namespaces.

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

**Step 2:** Add the following code to create a new button (Create Document) in your application.

```html
<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 3:**  Then, add the following code in the **Excel.razor** file to create and download the Excel file.

```js
@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 4:**  Now, create a new class file named **ExcelService**  in the **Data** folder.  Then, create a new method   **CreateExcel** and include the following code to export data to Excel document in your Blazor server-side application.

**Note: ** We can export data from the [ADO.NET](https://en.wikipedia.org/wiki/ADO.NET "Link to the Wikipedia article ") objects such as [datatable](https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/dataset-datatable-dataview/datatables "Link to the Microsoft documenation on DataTables"), [datacolumn](https://docs.microsoft.com/en-us/dotnet/api/system.data.datacolumn "Link to the Microsoft documenation on DataColumn"), and [dataview](https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/dataset-datatable-dataview/dataviews "Link to the Microsoft documenation on DataViews") to Excel worksheets. The exporting can be done as column headers by recognizing column types or cell value types, like hyperlinks, and a large dataset, all in just a few seconds. You can find the various easy ways to export data to Excel in the blog, [6 easy ways to Export data to Excel in C#](https://www.syncfusion.com/blogs/post/6-easy-ways-to-export-data-to-excel-in-c-sharp.aspx "Link to the article 6 Easy Ways to Export Data to Excel in C#").

We are going  to export data from a data table to Excel worksheets in **Blazor** platform using the Excel library’s [ImportDataTable](https://help.syncfusion.com/file-formats/xlsio/working-with-data#import-data-from-datatable "Link to Import data from DataTable in Excel Library documenattion") method.

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

namespace ServerSideApplication.Data
{
    public class ExcelService
    {
        public MemoryStream CreateExcel()
        {
            //Create an instance of ExcelEngine.
            using (ExcelEngine excelEngine = new ExcelEngine())
            {
                IApplication application = excelEngine.Excel;
                application.DefaultVersion = ExcelVersion.Xlsx;

                //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();

                //Export data from DataTable to Excel worksheet.
                worksheet.ImportDataTable(table, true, 1, 1);

                worksheet.UsedRange.AutofitColumns();

                //Save the document as a stream and return the stream.
                using (MemoryStream stream = new MemoryStream())
                {
                    //Save the created Excel document to MemoryStream.
                    workbook.SaveAs(stream);
                    return stream;
                }
            }
            return null; 
        }

        private DataTable SampleDataTable()
        {
            DataTable reports = new DataTable();

            reports.Columns.Add("SalesPerson");
            reports.Columns.Add("Age", typeof(int));
            reports.Columns.Add("Salary", typeof(int));

            reports.Rows.Add("Andy Bernard", 21, 30000);
            reports.Rows.Add("Jim Halpert",25, 40000);
            reports.Rows.Add("Karen Fillippelli", 30, 50000);
            reports.Rows.Add("Phyllis Lapin", 34, 39000);
            reports.Rows.Add("Stanley Hudson", 45, 58000);

            return reports;
        }

    }
}
```

Next, add the below service code under **ConfigureServices** method in the **Startup.cs** file.

```csharp
public void ConfigureServices(IServiceCollection services)
{
    services.AddRazorPages();
    services.AddServerSideBlazor();
    services.AddSingleton<WeatherForecastService>();
    services.AddSingleton<ExcelService>();
}
```

**Step 5:**  Then, create a new class file in the project named **FileUtils** and add the following code to invoke the JavaScript action for downloading the file in a browser.

```csharp
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 6:** Add the  **saveAsFile** JavaScript function in the **\_Host.cshtml** file present under the **Pages** folder.

```html
<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>
```

### #4 Run the application

Add the  **Excel**   page in the navigation panel in **NavMenu.razor**  file under the Shared folder and then run the application.

```html
<li class="nav-item px-3">
  <NavLink class="nav-link" href="excel">
   <span class="oi oi-list-rich" aria-hidden="true"></span> Excel
  </NavLink>
</li>
```

### #5 Download the output Excel document

Finally, navigate to the Excel page in your application and click on the **Create Document** button.

![Navigate to the Excel page and click on Create Document button](https://www.syncfusion.com/blogs/wp-content/uploads/2021/03/Navigate-to-the-Excel-page-and-click-on-Create-Document-button.png)

Then, we will get the output Excel file like in the following screenshot.

![Exporting data to Excel in Blazor Server-side application](https://www.syncfusion.com/blogs/wp-content/uploads/2021/03/Exporting-data-to-Excel-in-Blazor-Server-side-application.png)<figcaption>Exporting data to Excel in Blazor Server-side application</figcaption>

## Client-side application

### Create a client-side application

Create a new C# Blazor client-side application similar to the creation [server-side application](#create-a-server-side-application). Here, you have to choose the **Blazor WebAssembly App** option from the list like in the following screenshot.

### ![Select Blazor WebAssembly App](https://www.syncfusion.com/blogs/wp-content/uploads/2021/03/Select-Blazor-WebAssembly-App.png)Install the XlsIO package

Install the [Syncfusion.XlsIO.Net.Core](https://www.nuget.org/packages/Syncfusion.XlsIO.Net.Core "Link to install the Syncfusion.XlsIO.Net.Core NuGet package") NuGet package as a reference to your Blazor application from [NuGet.org](https://www.nuget.org/ "Link to the NuGet Gallery").

### Add necessary code to the client-side application

**Step 1:** Create a Razor file with the name **Excel**  in the **Pages** folder and include the following namespaces in it.

```js
@page "/Excel"
@using Syncfusion.XlsIO;
@using Syncfusion.Drawing;
@using System.IO;
@inject Microsoft.JSInterop.IJSRuntime JS
@using System.Data;
```

**Step 2:**  Then, add the following code to create a new button (Create Document) in your application.

```html
<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 3:** Add the following code in the **Excel.razor** file. In it, create a new method with the name **CreateDocument** to create, download and export data to the Excel document in the Blazor client-side application.

```js
@code{
    /// <summary>
    /// Create an Excel document.
    /// </summary>
public async void CreateDocument()
{
    //Create an instance of ExcelEngine.
    using (ExcelEngine excelEngine = new ExcelEngine())
    {
        IApplication application = excelEngine.Excel;
        application.DefaultVersion = ExcelVersion.Xlsx;

        //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();

        //Export data from DataTable to Excel worksheet.
        worksheet.ImportDataTable(table, true, 1, 1);

        worksheet.UsedRange.AutofitColumns();

        //Save the document as a stream and return the stream.
        using (MemoryStream stream = new MemoryStream())
        {
            //Save the created Excel document to MemoryStream
            workbook.SaveAs(stream);

            //Download the excel file.
            await JS.SaveAs("Sample.xlsx", stream.ToArray());
        }
    }
}
private DataTable SampleDataTable()
{
    DataTable reports = new DataTable();
    reports.Columns.Add("SalesPerson");
    reports.Columns.Add("Age", typeof(int));
    reports.Columns.Add("Salary", typeof(int));
    reports.Rows.Add("Andy Bernard", 21, 30000);
    reports.Rows.Add("Jim Halpert", 25, 40000);
    reports.Rows.Add("Karen Fillippelli", 30, 50000);
    reports.Rows.Add("Phyllis Lapin", 34, 39000);
    reports.Rows.Add("Stanley Hudson", 45, 58000);

    return reports;
}
}
```

**Step 4:**  Now, create a new class file in the project, with the name **FileUtils** the same as in the [server-side application](#add-necessary-code-to-server-side-application).

**Step 5:**  Then, add the saveAsFile JavaScript function in the **\_Host.cshtml** file present in the  **Pages** folder the same as for the [server-side application](#add-necessary-code-to-server-side-application).

### Run the application

Now, add the  **Excel**  page in the navigation panel in the  **NavMenu.razor**  file under the Shared folder. Then, run the application the same as for the [server-side application](#run-the-application).

### Download the output Excel document

Finally, navigate to the Excel page in your app and click   **Create Document**.  
 ![Navigate to the Excel page and click on Create Document button](https://www.syncfusion.com/blogs/wp-content/uploads/2021/03/Navigate-to-the-Excel-page-and-click-on-Create-Document-button-1.png)

Then, we will get the output Excel document like in the following screenshot.

![Exporting data to Excel in Blazor Client-side application](https://www.syncfusion.com/blogs/wp-content/uploads/2021/03/Exporting-data-to-Excel-in-Blazor-Client-side-application.png)<figcaption>Exporting data to Excel in Blazor Client-side application</figcaption>

## Resources

For more information, refer to the example [Export data to Excel in Blazor application](https://github.com/SyncfusionExamples/export-data-to-excel-in-blazor "Link to Export data to Excel in Blazor demo on GitHub").

## Conclusion

As you can see, it’s easy to create an Excel file, export data from data table to a worksheet,  and download the output file in the Blazor platform with the Syncfusion [Excel library](https://www.syncfusion.com/excel-framework/net "Link to the Syncfusion Excel Library") (XlsIO).

Use the library to generate Excel reports with high performance and to process large amounts of data. Take a moment to peruse our [documentation](https://help.syncfusion.com/file-formats/xlsio/working-with-data#importing-data-to-worksheets "Link to Working with data in Excel library documentation"), where you’ll find other options and features, all with accompanying code examples. Also, use this library to export Excel data to [PDF](https://help.syncfusion.com/file-formats/xlsio/excel-to-pdf-conversion "Link to Excel to PDF conversion in Excel documentation"), [image](https://help.syncfusion.com/file-formats/xlsio/worksheet-to-image-conversion "Link to worksheet to image conversion in Excel documentation"), [data table](https://help.syncfusion.com/file-formats/xlsio/working-with-data#exporting-from-worksheet-to-data-table "Link to export data from worksheet to data table in Excel documentation"), [CSV](https://www.syncfusion.com/kb/9092/convert-excel-file-to-csv-in-c-vb-net "Link to convert Excel files to CSV in C# and VB.NET Knowledge Base"), [TSV](https://www.syncfusion.com/kb/8556/does-xlsio-support-tsv-files "Link to covert Excel files to TSV Knowledge Base"), [HTML](https://help.syncfusion.com/file-formats/xlsio/working-with-excel-worksheet#save-worksheet-as-html "Link to save Excel worksheet as HTML documentation"), [collections of objects](https://help.syncfusion.com/file-formats/xlsio/working-with-data#exporting-from-worksheet-to-collection-objects "Link to export data from Excel worksheet to collection of objects documentation"), [ODS](https://help.syncfusion.com/file-formats/xlsio/excel-to-ods-conversion "Link to Excel to ODS conversion documentation") file formats, and more.

Are you already a Syncfusion user? You can download our products from the [product setup](https://www.syncfusion.com/account/downloads/studio/ "Link to license and download page of Essential Studio"). If you’re not yet a Syncfusion user, you can download a [30-day free trial](https://www.syncfusion.com/downloads "Link to the free evaluation of the Syncfusion Essential Studio").

If you have any questions, please let us know in the comments below. You can also contact us through our [support forum](https://www.syncfusion.com/forums "Link to the Syncfusion support forum") or [Direct-Trac](https://www.syncfusion.com/support/directtrac/ "Link to the Syncfusion support system Direct Trac") or [Feedback Portal](https://www.syncfusion.com/feedback/ "Link to Syncfusion Feedback Portal"). We are happy to assist you!

## Related Blogs

- [6 Easy Ways to Export Data to Excel in C#](https://www.syncfusion.com/blogs/post/6-easy-ways-to-export-data-to-excel-in-c-sharp.aspx "Link to the article 6 Easy Ways to Export Data to Excel in C#")
- [How to Export Data from SQL Server to Excel Table in C#](https://dev.to/syncfusion/how-to-export-data-from-sql-server-to-excel-table-in-c-fo7 "Link to the article How to Export Data from SQL Server to Excel Table in C#")
- [Easy Steps to Export HTML Tables to an Excel Worksheet in C#](https://dev.to/syncfusion/easy-steps-to-export-html-tables-to-an-excel-worksheet-in-c-4je1 "Link to the article Easy Steps to Export HTML Tables to an Excel Worksheet in C#")
- [Export Data from Collection to Excel and Group It in C#](https://dev.to/karthickramasamy08/export-data-from-collection-to-excel-and-group-it-in-c-1j65-temp-slug-6071060 "Link to the article Export Data from Collection to Excel and Group It in C#")
- [Export Data to a Predefined Excel Template in C#](https://dev.to/sureshmohan/export-data-to-a-predefined-excel-template-in-c-dp6 "Link to the article Export Data to a Predefined Excel Template in C#")