USING IRONXL

IronXL: C# Excel Library

IronXL is a C# Excel library designed to take care of the most time-consuming tasks in Excel, those that are repeated many times. IronXL is powerful enough to handle even the most complex problems in Excel. It can deal with huge datasets and large cells with ease, which has been a difficult task for a lot of developers who use Excel for their work. This library helps them develop applications that can read and directly write Excel data without the need to interface with Microsoft Office files or libraries on Windows.

IronXL library can be used to create a variety of spreadsheets such as invoices, expense reports, or sales reports. Moreover, it can help streamline data analysis or reporting processes in your workplace by automating tasks like merging complex data sets. IronXL supports multiple file formats.

IronXL's primary feature enables developers to create, edit, manipulate, and read Excel files without requiring Microsoft Excel. This means there's no need to install Microsoft Excel on your system. This functionality offers various possibilities for developers, simplifying the integration of Excel data within applications. For example, a developer can automatically generate reports from a database and export them to Excel for easy distribution. For a detailed guide on reading Excel files in C#, refer to this C# Read Excel file tutorial.

using IronXL;

class Program
{
    static void Main()
    {
        // Set the license key for IronXL
        License.LicenseKey = "Your-License-Key"; // Ensure the correct license key is set

        // Load an existing Excel file
        WorkBook workbook = WorkBook.Load("ExistingData.xlsx");
        WorkSheet sheet = workbook.DefaultWorkSheet;

        // For example, changing the sales value in cell C2
        if (!sheet["C2"].IsEmpty)
        {
            double currentSales = sheet["C2"].DoubleValue;
            // Increase sales by 10%
            sheet["C2"].Value = currentSales * 1.10;
        }

        // Save the changes back to the same file or a new file
        workbook.SaveAs("UpdatedData.xlsx");
    }
}
using IronXL;

class Program
{
    static void Main()
    {
        // Set the license key for IronXL
        License.LicenseKey = "Your-License-Key"; // Ensure the correct license key is set

        // Load an existing Excel file
        WorkBook workbook = WorkBook.Load("ExistingData.xlsx");
        WorkSheet sheet = workbook.DefaultWorkSheet;

        // For example, changing the sales value in cell C2
        if (!sheet["C2"].IsEmpty)
        {
            double currentSales = sheet["C2"].DoubleValue;
            // Increase sales by 10%
            sheet["C2"].Value = currentSales * 1.10;
        }

        // Save the changes back to the same file or a new file
        workbook.SaveAs("UpdatedData.xlsx");
    }
}
Imports IronXL



Friend Class Program

	Shared Sub Main()

		' Set the license key for IronXL

		License.LicenseKey = "Your-License-Key" ' Ensure the correct license key is set



		' Load an existing Excel file

		Dim workbook As WorkBook = WorkBook.Load("ExistingData.xlsx")

		Dim sheet As WorkSheet = workbook.DefaultWorkSheet



		' For example, changing the sales value in cell C2

		If Not sheet("C2").IsEmpty Then

			Dim currentSales As Double = sheet("C2").DoubleValue

			' Increase sales by 10%

			sheet("C2").Value = currentSales * 1.10

		End If



		' Save the changes back to the same file or a new file

		workbook.SaveAs("UpdatedData.xlsx")

	End Sub

End Class
$vbLabelText   $csharpLabel

Export Data to Excel from Blazor Project

Let's follow the steps to create an Excel file from a Blazor Web Application.

Prerequisites

For exporting Excel files in a Blazor Server Application, there are some prerequisites:

  1. Visual Studio (the latest Version)
  2. .NET Framework 6 or 7
  3. Running Blazor Server Application in Visual Studio
  4. Stable Internet Connection to install IronXL library

Install IronXL library

Now, it's time to install the IronXL library using the NuGet Package Manager Console. Open the NuGet Package Manager Console and write the following command:

Install-Package IronXL.Excel

This command will install the latest version of IronXL in the application.

Code to Download Exported Excel file

After installing IronXL, create a folder with the name "js" under the "wwwroot" section from within the Solution Explorer. In the "js" folder, create a JavaScript file with the name "SaveAsFile.js." as shown in the following screenshot.

How to Export Data to Excel in Blazor Using IronXL, Figure 1: js Folder js Folder

Now, add the following code in the "SaveAsFile.js" file. This function will return generated files to users as a stream.

function saveAsFile(filename, byteBase64) {
    var link = document.createElement('a');
    link.download = filename;
    link.href = "data:application/octet-stream;base64," + byteBase64;
    document.body.appendChild(link); // Needed for Firefox link
    link.click();
    document.body.removeChild(link);
}
function saveAsFile(filename, byteBase64) {
    var link = document.createElement('a');
    link.download = filename;
    link.href = "data:application/octet-stream;base64," + byteBase64;
    document.body.appendChild(link); // Needed for Firefox link
    link.click();
    document.body.removeChild(link);
}
JAVASCRIPT

Next, add the relative path to the "SaveAsFile.js" file in the "_Host.cshtml" file. This will allow the application to invoke the JavaScript function previously defined.

<script src="~/js/SaveAsFile.js"></script>
<script src="~/js/SaveAsFile.js"></script>
HTML

Code to Export Excel file

Create a class named "ExcelExport.cs" under the Data folder.

How to Export Data to Excel in Blazor Using IronXL, Figure 2: ExcelExport.cs ExcelExport.cs

Write the following code for exporting data in the "ExcelExport.cs" file.

using IronXL;
using Microsoft.JSInterop;
using System;

namespace Export_Excel_Blazor.Data
{
    public class ExcelExport
    {
        public void ExcelGenerate(IJSRuntime iJSRuntime)
        {
            byte[] fileContents;
            WorkBook xlsxWorkbook = WorkBook.Create(IronXL.ExcelFileFormat.XLSX);
            xlsxWorkbook.Metadata.Author = "IronXL";

            // Add a blank WorkSheet
            WorkSheet xlsxSheet = xlsxWorkbook.CreateWorkSheet("new_sheet");

            // Add data and styles to the new worksheet
            xlsxSheet["A1"].Value = "Product EN";
            xlsxSheet["B1"].Value = "SKU";
            xlsxSheet["C1"].Value = "Customer";

            xlsxSheet["A1:C1"].Style.Font.Bold = true;

            xlsxSheet["A2"].Value = "Iron Rods";
            xlsxSheet["A3"].Value = "Mobile Phones";
            xlsxSheet["A4"].Value = "Chargers";

            xlsxSheet["B2"].Value = "105";
            xlsxSheet["B3"].Value = "285";
            xlsxSheet["B4"].Value = "301";

            xlsxSheet["C2"].Value = "Adam";
            xlsxSheet["C3"].Value = "Ellen";
            xlsxSheet["C4"].Value = "Tom";

            fileContents = xlsxWorkbook.ToByteArray();

            // Trigger JavaScript function to download the file
            iJSRuntime.InvokeAsync<object>(
                "saveAsFile",
                "GeneratedExcel.xlsx",
                Convert.ToBase64String(fileContents)
            );
        }
    }
}
using IronXL;
using Microsoft.JSInterop;
using System;

namespace Export_Excel_Blazor.Data
{
    public class ExcelExport
    {
        public void ExcelGenerate(IJSRuntime iJSRuntime)
        {
            byte[] fileContents;
            WorkBook xlsxWorkbook = WorkBook.Create(IronXL.ExcelFileFormat.XLSX);
            xlsxWorkbook.Metadata.Author = "IronXL";

            // Add a blank WorkSheet
            WorkSheet xlsxSheet = xlsxWorkbook.CreateWorkSheet("new_sheet");

            // Add data and styles to the new worksheet
            xlsxSheet["A1"].Value = "Product EN";
            xlsxSheet["B1"].Value = "SKU";
            xlsxSheet["C1"].Value = "Customer";

            xlsxSheet["A1:C1"].Style.Font.Bold = true;

            xlsxSheet["A2"].Value = "Iron Rods";
            xlsxSheet["A3"].Value = "Mobile Phones";
            xlsxSheet["A4"].Value = "Chargers";

            xlsxSheet["B2"].Value = "105";
            xlsxSheet["B3"].Value = "285";
            xlsxSheet["B4"].Value = "301";

            xlsxSheet["C2"].Value = "Adam";
            xlsxSheet["C3"].Value = "Ellen";
            xlsxSheet["C4"].Value = "Tom";

            fileContents = xlsxWorkbook.ToByteArray();

            // Trigger JavaScript function to download the file
            iJSRuntime.InvokeAsync<object>(
                "saveAsFile",
                "GeneratedExcel.xlsx",
                Convert.ToBase64String(fileContents)
            );
        }
    }
}
Imports IronXL

Imports Microsoft.JSInterop

Imports System



Namespace Export_Excel_Blazor.Data

	Public Class ExcelExport

		Public Sub ExcelGenerate(ByVal iJSRuntime As IJSRuntime)

			Dim fileContents() As Byte

			Dim xlsxWorkbook As WorkBook = WorkBook.Create(IronXL.ExcelFileFormat.XLSX)

			xlsxWorkbook.Metadata.Author = "IronXL"



			' Add a blank WorkSheet

			Dim xlsxSheet As WorkSheet = xlsxWorkbook.CreateWorkSheet("new_sheet")



			' Add data and styles to the new worksheet

			xlsxSheet("A1").Value = "Product EN"

			xlsxSheet("B1").Value = "SKU"

			xlsxSheet("C1").Value = "Customer"



			xlsxSheet("A1:C1").Style.Font.Bold = True



			xlsxSheet("A2").Value = "Iron Rods"

			xlsxSheet("A3").Value = "Mobile Phones"

			xlsxSheet("A4").Value = "Chargers"



			xlsxSheet("B2").Value = "105"

			xlsxSheet("B3").Value = "285"

			xlsxSheet("B4").Value = "301"



			xlsxSheet("C2").Value = "Adam"

			xlsxSheet("C3").Value = "Ellen"

			xlsxSheet("C4").Value = "Tom"



			fileContents = xlsxWorkbook.ToByteArray()



			' Trigger JavaScript function to download the file

			iJSRuntime.InvokeAsync(Of Object)("saveAsFile", "GeneratedExcel.xlsx", Convert.ToBase64String(fileContents))

		End Sub

	End Class

End Namespace
$vbLabelText   $csharpLabel

In the above example, the IronXL library creates an Excel WorkBook in XLSX format. IronXL also supports the XLS format. A WorkBook is necessary to have a WorkSheet added. The next step is to fill this sheet with dummy data.

After that, the whole WorkBook content is converted to the byte array and IJSRuntime is triggered to download the file with the following parameters: the name of the JavaScript function, the file name for the exported file, and WorkBook's byte array.

Create Razor Component

Create a Razor component named "ExportExcel.razor" under the Pages folder.

How to Export Data to Excel in Blazor Using IronXL, Figure 3: ExportExcel.cs

Next, replace the source code of "ExportExcel.razor" with the one given below.

@page "/export"
@using Export_Excel_Blazor.Data
@inject IJSRuntime JS

<h1>IronXL Export Excel File</h1>

<p>Intuitive C# & VB.NET Excel API & No need to install MS Office or Excel Interop</p>

<button class="btn btn-primary" @onclick="ExcelGeneration">Create Excel File</button>

@code {
    private void ExcelGeneration()
    {
        ExcelExport excelExport = new ExcelExport();
        excelExport.ExcelGenerate(JS);
    }
}

In the above HTML code, create a button with an onclick property pointing to the ExcelGeneration function. Then, the ExcelGeneration function inside the @code section is added with C# code to handle the export function.

Add the following piece of code in the "NavMenu.razor" file. It'll add a nav bar menu to reach the Excel Generation page.

<li class="nav-item px-3">
    <NavLink class="nav-link" href="export">
        <span class="oi oi-list-rich" aria-hidden="true"></span> Export Excel
    </NavLink>
</li>
<li class="nav-item px-3">
    <NavLink class="nav-link" href="export">
        <span class="oi oi-list-rich" aria-hidden="true"></span> Export Excel
    </NavLink>
</li>
HTML

Run Project

Finally, run the project. You'll see the following output in the browser. Go to the "Export Excel" nav menu and click on the "Create Excel File" button.

How to Export Data to Excel in Blazor Using IronXL, Figure 4: ExportExcel.razor ExportExcel.razor

The application will export data to an Excel spreadsheet and download the XLSX file to your machine.

How to Export Data to Excel in Blazor Using IronXL, Figure 5: Download Excel Download Excel

Generated Excel Spreadsheet

This is the preview of the generated Excel file.

How to Export Data to Excel in Blazor Using IronXL, Figure 6: Generated Excel Generated Excel

Summary

This article went through the process of generating and exporting Excel files in the Blazor application using IronXL. IronXL is a great tool for .NET developers who have to manipulate Excel files in the software without installing Microsoft Office on the machine. IronXL provides a much faster way to build Excel files in .NET.

IronXL is built on top of the C# language and provides fast and easy code development for building interactive and highly responsive user interfaces in the world's most popular spreadsheet application. Microsoft Interop is a relatively slower library with more complex coding required. Microsoft Interop is slower than IronXL because it requires the use of COM for reading and writing data. Explore more articles related to IronXL on how to export Excel files, control the way that cells are displayed in an Excel workbook with gridlines, chart management, and text alignment, font size, color.

Frequently Asked Questions

What is the purpose of the tutorial on the IronXL page?

The tutorial aims to simplify the process of exporting data to Excel files in a Blazor Server App using the IronXL library, without the need for additional component installation.

How can you export data to Excel in a Blazor Web Application using IronXL?

To export data to Excel in a Blazor Web Application, you need to create a Blazor project, install the IronXL library, use its APIs to create and fill an Excel workbook, convert it to a Byte Array, and then use JavaScript to download the file.

What are the prerequisites for exporting Excel files in a Blazor Server Application?

The prerequisites include having Visual Studio, .NET Framework 6 or 7, a running Blazor Server Application, and a stable internet connection to install the IronXL library.

What is IronXL, and why is it beneficial for developers?

IronXL is a C# Excel library that allows developers to create, edit, manipulate, and read Excel files without requiring Microsoft Excel. This is beneficial as it simplifies Excel data integration within applications and eliminates the need to install Microsoft Excel.

How do you install the IronXL library in a Blazor project?

You can install the IronXL library using the NuGet Package Manager Console in Visual Studio with the command: Install-Package IronXL.Excel.

How does IronXL compare to Microsoft Interop for Excel file manipulation?

IronXL is faster and easier to use compared to Microsoft Interop, which is slower due to its reliance on COM for reading and writing data. IronXL allows for faster code development and does not require Microsoft Office installation.

What kind of applications can benefit from using the IronXL library?

Applications that require Excel file manipulation, such as generating reports, invoices, or sales data, can benefit from using IronXL. It helps automate tasks like merging complex datasets and streamlines data analysis and reporting processes.

What is the role of JavaScript in exporting Excel files using IronXL in Blazor?

JavaScript is used to trigger the download of the generated Excel file by converting the workbook's byte array to a Base64 string and then invoking a JavaScript function to save the file on the user's machine.

Can IronXL handle large datasets and complex Excel operations?

Yes, IronXL is powerful enough to handle huge datasets and complex Excel operations, making it suitable for developers working with large amounts of data.

Is it necessary to have Microsoft Excel installed to use IronXL?

No, it is not necessary to have Microsoft Excel installed to use IronXL, as it allows for creating and manipulating Excel files independently of Microsoft Office.

Regan Pun
Software Engineer
Regan graduated from the University of Reading, with a BA in Electronic Engineering. Before joining Iron Software, his previous job roles had him laser-focused on single tasks; and what he most enjoys at Iron Software is the spectrum of work he gets to undertake, whether it’s adding value to sales, technical support, product development or marketing. He enjoys understanding the way developers are using the Iron Software library, and using that knowledge to continually improve documentation and develop the products.
< PREVIOUS
C# CSV Parser (Step-By-Step) Tutorial
NEXT >
How to Generate an Excel File on Razor Pages