Passer au contenu du pied de page
UTILISATION D'IRONXL

Comment générer un fichier Excel sur Razor Pages

Razor Pages offer a modern approach to building web pages. In Razor Pages, the source code that renders the web page is written in C# rather than being generated by a server-side page.

To efficiently work with Excel files, the IronXL library is recommended over others like the POI Java project NPOI package (notably used with PowerPoint files) and Office Interop. IronXL is a feature-rich, easy-to-use library that doesn't require Microsoft Office and supports multiple .NET versions.

This article demonstrates using the IronXL C# library to generate and export Excel spreadsheets with dummy data and row headers in Razor Pages.

IronXL: C# Excel Library

IronXL is a C# Excel library that offers methods and functions for operating on large data sets using parallel processing to increase computing power. It's user-friendly as it doesn't require understanding the inner workings and supports both XLS and XLSX files.

IronXL is ideal for importing, exporting, creating Excel formulas, and office documents without needing Microsoft Office to be installed.

Learn how to import and export Excel files in Razor Pages using IronXL.

Generate Excel File in Razor Pages

To create Excel sheets in Razor Pages, start by opening Visual Studio, creating an ASP.NET Core Web Application, and installing IronXL.

Prerequisites

Setting up to create Excel files in Razor Pages requires:

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

Install IronXL Library

Install IronXL using the NuGet Package Manager Console. Enter this command to install the library in a .NET Core Web Application:

Install-Package IronXL.Excel

Code for Generating Excel file

Here's how to write the code. Open "Index.cs" in the Pages folder and add the following method:

public FileResult OnPostExport()
{
    // Create a new WorkBook with XLSX format
    WorkBook workBook = new WorkBook(IronXL.ExcelFileFormat.XLSX);
    // Create a new WorkSheet named "data"
    WorkSheet workSheet = workBook.CreateWorkSheet("data");

    // Add headers to the new worksheet
    workSheet["A1"].Value = "Product EN";
    workSheet["B1"].Value = "SKU";
    workSheet["C1"].Value = "Customer";

    // Make header text bold
    workSheet["A1:C1"].Style.Font.Bold = true;

    // Add dummy data to the worksheet
    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";

    // Convert the WorkBook to a byte array Stream for download
    return File(workBook.ToStream().ToArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Grid.xlsx");
}
public FileResult OnPostExport()
{
    // Create a new WorkBook with XLSX format
    WorkBook workBook = new WorkBook(IronXL.ExcelFileFormat.XLSX);
    // Create a new WorkSheet named "data"
    WorkSheet workSheet = workBook.CreateWorkSheet("data");

    // Add headers to the new worksheet
    workSheet["A1"].Value = "Product EN";
    workSheet["B1"].Value = "SKU";
    workSheet["C1"].Value = "Customer";

    // Make header text bold
    workSheet["A1:C1"].Style.Font.Bold = true;

    // Add dummy data to the worksheet
    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";

    // Convert the WorkBook to a byte array Stream for download
    return File(workBook.ToStream().ToArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Grid.xlsx");
}
Public Function OnPostExport() As FileResult
	' Create a new WorkBook with XLSX format
	Dim workBook As New WorkBook(IronXL.ExcelFileFormat.XLSX)
	' Create a new WorkSheet named "data"
	Dim workSheet As WorkSheet = workBook.CreateWorkSheet("data")

	' Add headers to the new worksheet
	workSheet("A1").Value = "Product EN"
	workSheet("B1").Value = "SKU"
	workSheet("C1").Value = "Customer"

	' Make header text bold
	workSheet("A1:C1").Style.Font.Bold = True

	' Add dummy data to the worksheet
	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"

	' Convert the WorkBook to a byte array Stream for download
	Return File(workBook.ToStream().ToArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Grid.xlsx")
End Function
$vbLabelText   $csharpLabel

In this code, a new Excel WorkBook is created and contains one WorkSheet. The sheet is populated with dummy data, and the generated file is responded to the server with:

  • The WorkBook is converted to a Stream to download as a file.
  • The MIME type is set.
  • A name for the file download is specified.

Create a button to download the Excel file

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

@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# that 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# that 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

This HTML creates a form with asp-page-handler set to "Export", enabling the application to export the Excel file to the local machine when the user clicks the "Generate Excel File!" button, triggering a browser download.

Run the Project

Run the project, and you'll see a screen in the browser. Click 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

After clicking "Generate Excel File!", the file will download.

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

Open the Generated Excel File

The generated Excel file's content matches the code's output with perfect formatting. The snapshot of the generated Excel file is displayed below.

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

IronXL better than Competitors

IronXL is a superior tool for working with both XLS and XLSX formats without limitations like NPOI, which is slower due to being Java-based, whereas IronXL is C#. In ASP.NET Core applications generating large/multiple spreadsheets, opt for IronXL over POI.

IronXL allows for creating and editing Excel files without Microsoft Office. Unlike Microsoft Interop, IronXL does not need to call Microsoft Excel's ActiveX for Excel operations or exports. It also allows exporting CSV files to Excel format.

IronXL also provides extensive features for interacting with Excel files, including converting between popular formats, inserting math functions, adding charts, and inserting images.

Conclusion

This article showcases using IronXL for generating an Excel file in Razor Pages without needing Microsoft Excel ActiveX and facilitating file downloads.

Explore more tutorials on creating Excel files.

IronXL is free for non-commercial development. A free trial is available for production testing. View pricing plans for more pricing and licensing details.

Questions Fréquemment Posées

Comment puis-je générer un fichier Excel dans Razor Pages sans utiliser Interop?

Vous pouvez générer un fichier Excel dans Razor Pages sans utiliser Interop en utilisant la bibliothèque IronXL. Cette bibliothèque vous permet de créer et manipuler des fichiers Excel directement en C#, sans avoir besoin de Microsoft Office, en créant un WorkBook et en ajoutant des données à une WorkSheet.

Quelles sont les étapes impliquées dans l'installation de IronXL pour un projet Razor Pages?

Pour installer IronXL pour un projet Razor Pages, vous pouvez utiliser la console du gestionnaire de packages NuGet dans Visual Studio. Exécutez la commande Install-Package IronXL.Excel pour ajouter la bibliothèque à votre projet.

Puis-je utiliser IronXL pour exporter des données depuis une application Razor Pages?

Oui, IronXL peut être utilisé pour exporter des données depuis une application Razor Pages. Vous pouvez convertir vos données au format Excel, puis utiliser Razor Pages pour retransmettre ces données au client sous forme de fichier téléchargeable.

Quels sont les avantages d'utiliser IronXL plutôt que Microsoft Interop pour générer des fichiers Excel?

IronXL offre plusieurs avantages par rapport à Microsoft Interop, notamment une performance plus rapide, aucune nécessité d'installation de Microsoft Office, et la capacité de gérer des ensembles de données volumineux efficacement grâce au traitement parallèle.

Est-il possible de gérer de grandes ensembles de données Excel dans Razor Pages en utilisant IronXL?

Oui, IronXL est capable de gérer efficacement de grandes ensembles de données Excel. Il prend en charge le traitement parallèle, ce qui peut améliorer la performance et la vitesse lors de la manipulation de données étendues.

IronXL prend-il en charge différents formats de fichiers Excel?

IronXL prend en charge les formats de fichiers XLS et XLSX, permettant une manipulation complète des fichiers Excel, y compris l'importation, l'exportation, et le formatage des données.

Existe-t-il des options gratuites pour utiliser IronXL en développement?

IronXL est disponible gratuitement pour le développement non commercial. Un essai gratuit est fourni pour les tests de production, avec divers plans tarifaires disponibles pour une utilisation commerciale.

Comment puis-je déclencher un téléchargement de fichier Excel dans Razor Pages en utilisant IronXL?

Pour déclencher un téléchargement de fichier Excel dans Razor Pages en utilisant IronXL, créez un WorkBook, remplissez-le avec des données, puis convertissez-le en un tableau d'octets. Utilisez la méthode File de Razor Pages pour diffuser le tableau d'octets en tant que fichier téléchargeable pour l'utilisateur.

Qu'est-ce qui fait de IronXL un choix préférable par rapport à d'autres bibliothèques comme NPOI?

IronXL est souvent préféré par rapport aux bibliothèques comme NPOI en raison de son implémentation native en C#, qui offre une performance plus rapide, une facilité d'utilisation, et aucune dépendance aux composants Java, ce qui en fait un choix idéal pour les applications ASP.NET Core.

Jordi Bardia
Ingénieur logiciel
Jordi est le plus compétent en Python, C# et C++, et lorsqu'il ne met pas à profit ses compétences chez Iron Software, il programme des jeux. Partageant les responsabilités des tests de produit, du développement de produit et de la recherche, Jordi apporte une immense valeur à l'amé...
Lire la suite