How to Generate an Excel File on Razor Pages

Introduction

Razor Pages are a new way to build web pages. With Razor Pages, the source code that renders the web page is built in C# instead of being generated by a server-side page.

To work with Excel files efficiently, the IronXL library is recommended over other libraries such as the POI Java project NPOI package (which can also be used with PowerPoint files) and Office Interop. It provides a feature-rich library that is simple, easy-to-use, and doesn't require Microsoft Office. This library should also support multiple versions of .NET.

This article will demonstrate how to use the IronXL C# library to generate and export Excel spreadsheets with dummy data and row headers in Razor Pages (Page model).

IronXL: C# Excel Library

IronXL is a C# Excel library that provides methods and functions for operating on large data sets. It makes use of parallel processing to obtain more computing power. It's easy for programmers to use because it doesn't require any knowledge about how the process works behind the scenes. It supports XLS as well as XLSX files.

The IronXL also supports importing and exporting Excel files, as well as creating Excel formulas and office documents. It is the perfect solution for those who don't want to install Microsoft Office on their machines.

Let's see how to import and export Excel files in Razor Pages with IronXL.

Generate Excel File in Razor Pages

For creating Excel sheets in Razor Pages, open Visual Studio, create an ASP.NET Core Web Application and install IronXL.

Prerequisites

For creating Excel files in Razor Pages, there are some prerequisites:

  1. Visual Studio (Latest Version)
  2. .NET Framework 6 or 7
  3. .NET Core Web Application in Visual Studio

Install IronXL Library

You can install it using the NuGet Package Manager Console. Open the Console and write the following command to install the IronXL library in a .NET Core Web Application.

Install-Package IronXL.Excel

Code for Generating Excel file

Now, it's time to write code. Open the "Index.cs" file from the Pages folder and add the following method:

public FileResult OnPostExport()
{
    WorkBook workBook = new WorkBook(IronXL.ExcelFileFormat.XLSX);
    WorkSheet workSheet = workBook.CreateWorkSheet("data");

    //Add data and styles to the new worksheet

    workSheet["A1"].Value = "Product EN";
    workSheet["B1"].Value = "SKU";
    workSheet["C1"].Value = "Customer";

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

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

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

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

    return File(workBook.ToStream().ToArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Grid.xlsx");
}
public FileResult OnPostExport()
{
    WorkBook workBook = new WorkBook(IronXL.ExcelFileFormat.XLSX);
    WorkSheet workSheet = workBook.CreateWorkSheet("data");

    //Add data and styles to the new worksheet

    workSheet["A1"].Value = "Product EN";
    workSheet["B1"].Value = "SKU";
    workSheet["C1"].Value = "Customer";

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

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

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

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

    return File(workBook.ToStream().ToArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Grid.xlsx");
}
Public Function OnPostExport() As FileResult
	Dim workBook As New WorkBook(IronXL.ExcelFileFormat.XLSX)
	Dim workSheet As WorkSheet = workBook.CreateWorkSheet("data")

	'Add data and styles to the new worksheet

	workSheet("A1").Value = "Product EN"
	workSheet("B1").Value = "SKU"
	workSheet("C1").Value = "Customer"

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

	workSheet("A2").Value = "Iron Rods"
	workSheet("A3").Value = "Mobile Phones"
	workSheet("A4").Value = "Chargers"

	workSheet("B2").Value = "105"
	workSheet("B3").Value = "285"
	workSheet("B4").Value = "301"

	workSheet("C2").Value = "Adam"
	workSheet("C3").Value = "Ellen"
	workSheet("C4").Value = "Tom"

	Return File(workBook.ToStream().ToArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Grid.xlsx")
End Function
VB   C#

In the above code, a new Excel WorkBook is created, and it contains one WorkSheet. After that, the sheet is populated with dummy data and returns the generated file in a server response with the following parameters:

  • Convert the WorkBook to Stream (because it is important to convert the file into a stream before downloading it).
  • Set the data type
  • Specify the name of the file download.

Create a button to download the Excel file

Replace the existing code in "Index.cshtml" with the code below:

@page
@model IndexModel
@{
    ViewData["Title"] = "Home page";
}

<div class="text-center">
    <h1 class="display-4">IronXL Generate Excel File</h1>
    <p class="m-5">IronXL is an Excel Library for C# and allows developers to read and edit Excel data from XLS and XLSX documents without using Microsoft.Office.Interop.Excel</p>
    <form method="post" asp-page-handler="Export">
        <button class="btn btn-success p-3">Generate Excel File!</button>
    </form>
</div>
@page
@model IndexModel
@{
    ViewData["Title"] = "Home page";
}

<div class="text-center">
    <h1 class="display-4">IronXL Generate Excel File</h1>
    <p class="m-5">IronXL is an Excel Library for C# and allows developers to read and edit Excel data from XLS and XLSX documents without using Microsoft.Office.Interop.Excel</p>
    <form method="post" asp-page-handler="Export">
        <button class="btn btn-success p-3">Generate Excel File!</button>
    </form>
</div>
HTML

In the HTML code above, create a form tag with the property "asp-page-handler" set to "Export". This will enable the application to export an Excel file to the local machine. Additionally, create a button with the text "Generate Excel File!". When the user clicks on this button, it'll trigger the browser to download the generated Excel file.

Run the Project

Now run the project and you'll see the following screen in the browser. Click on the green button to download the Excel file.

How to Generate an Excel File on Razor Pages, Figure 1: IronXL Generate Excel Sheets IronXL Generate Excel Sheets

You'll see the downloaded file at the bottom when you click on the button "Generate Excel File!".

How to Generate an Excel File on Razor Pages, Figure 2: IronXL Downloaded File IronXL Downloaded File

Open the Generated Excel File

The content in the generated Excel file is consistent with what is written in the code, with perfect formatting. You can see the snapshot of the generated Excel file below.

How to Generate an Excel File on Razor Pages, Figure 3: IronXL Generated File IronXL Generated File

IronXL better than Competitors

The IronXL library is a more powerful tool to work with Excel that supports XLS as well as XLSX and does not have the limitations of NPOI. NPOI runs much slower compared to IronXL, as it is written in Java instead of in C#. Therefore, you will want to go for IronXL instead of POI when you want to generate large/multiple spreadsheets in ASP.NET Core applications.

IronXL is a great library for creating and editing Excel files without using Microsoft Office. Unlike Microsoft Interop, IronXL doesn't need to call Microsoft Excel's ActiveX in the background to perform Excel operations and to export to Excel. IronXL can work without the Microsoft Office suite. IronXL can also export CSV files to the Excel format.

Furthermore, IronXL also offers a wide range of features to interact with Excel files including converting between popular formats, inserting math functions, and even adding charts and inserting images.

Conclusion

This article presented how to use IronXL to generate an Excel file in Razor Pages, in a manner that does not require calling Microsoft Excel ActiveX and downloading the file.

Visit the following link for more tutorials on creating Excel files.

IronXL is free to use for non-commercial development purposes. A free trial is available for testing in production. Look at the pricing plans for more details about prices and licensing.