跳至页脚内容
使用 IRONXL

如何在 Razor 中导出 CSV 和 Excel

Looking for a way to export data to an Excel file using Razor Pages? This article instructs on how to do so using IronXL for .NET.

1. IronXL

IronXL is a .NET library used for working with Excel files. It is built on top of OpenXML SDK and provides a simple API for reading, writing, and manipulating Excel spreadsheets. IronXL can be used in a variety of .NET applications, including Web Applications, Desktop Applications, and Console Applications. IronXL provides a range of features for working with Excel documents, including the ability to read and write data to individual cells, create charts and graphs, and perform complex calculations. It also supports advanced Excel features such as pivot tables, conditional formatting, and data validation.

Exporting data to Excel and CSV files is a common task in web development, and Razor and IronXL make it easy to accomplish. With IronXL, developers can easily create Excel spreadsheets and save them to a file or stream. Razor can then be used to generate dynamic content that includes links to the Excel document, allowing users to download them directly from the web page. The CSV file format can also be generated using IronXL and downloaded similarly using Razor. This makes it simple to create reports and other data-driven content that can be easily shared with others. Overall, the combination of Razor and IronXL .NET Core Razor Pages provides a powerful toolset for web developers looking to create dynamic, data-driven web pages.

2. Prerequisites

Before using Razor in Visual Studio, there are a few prerequisites that users should have in place. Here are some of the important ones:

  1. As an IronXL user, you need to have Visual Studio installed on your computer system. You can download Visual Studio Community for free from the official website of Microsoft.
  2. You also need to have the .NET Core SDK installed on your computer. You can download the latest version of the .NET Core SDK from the official Microsoft website.
  3. Your Web Development environment must be set before starting to work with Razor View.

3. Creating a New Visual Studio Project

To create a new Visual Studio project, follow these steps:

  1. Open Visual Studio.
  2. Click on "Create a New Project" in the start window, or click on "File" > "New" > "Project" in the menu bar.

    How to Export CSV and Excel in Razor, Figure 1: Visual Studio's start window Visual Studio's start window

  3. Select the type of project you want to create, to use Razor Pages, select ASP.NET Core Web App and click on Next.

    How to Export CSV and Excel in Razor, Figure 2: Create a new .NET Core Web App in Visual Studio Create a new .NET Core Web App in Visual Studio

  4. A new window will appear, write your new project name and location. Then click on Next.

    How to Export CSV and Excel in Razor, Figure 3: Configure the new project Configure the new project

  5. Now in the new window select your target Framework, check the configure for HTTPS option and click on create.
  6. Just like that your new Visual Studio ASP.NET Core Web App Project is created.

4. Install IronXL

The IronXL Library can be downloaded and installed in different ways.

These are:

  • Using Visual Studio NuGet packages.
  • Using the Visual Studio Command Line.

4.1 Using Visual Studio

To install the IronXL library, the simplest approach is to use the NuGet Package Manager. Open the manager and search for IronXL in the browse tab. Choose IronXL from the search results and install it.

The below screenshot shows how to open the NuGet Package Manager in Visual Studio.

How to Export CSV and Excel in Razor, Figure 4: Navigate to NuGet Package Manager Navigate to NuGet Package Manager

IronXL in search results:

How to Export CSV and Excel in Razor, Figure 5: Search for IronXL in NuGet Package Manager UI Search for IronXL in NuGet Package Manager UI

4.2 Using the Visual Studio Command-Line

Using a console to perform operations is a popular choice for many. If you prefer to install IronXL through the command line, you can follow these steps:

  • In Visual Studio, go to Tools > NuGet Package Manager > Package Manager Console.
  • Enter the following line in the Package Manager Console tab, which will install the package:
Install-Package IronXL.Excel

Now the package will download/install to the current project and be ready to use.

How to Export CSV and Excel in Razor, Figure 6: Install IronXL in the Package Manager Console Install IronXL in the Package Manager Console

5. Export Data to an Excel File in Razor Net Core

Once the project is created, a simple interface of the Razor application is created. Now change the interface to export to Excel export.

How to Export CSV and Excel in Razor, Figure 7: The Web interface of the newly created project The Web interface of the newly created project

Change the above interface by editing the index.cshtml file in the Pages directory.

@page
@model IndexModel
@{
    ViewData["Title"] = "Home page";
}
<div class="text-center">
    <h1 class="display-4">IronXL Generate Excel File</h1>
    <p class="m-5">This will be the combination of Razor and IronXL, together they will Export data to Excel file.</p>
    <form method="post" asp-page-handler="Export">
        <button class="btn btn-success p-3">Export 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">This will be the combination of Razor and IronXL, together they will Export data to Excel file.</p>
    <form method="post" asp-page-handler="Export">
        <button class="btn btn-success p-3">Export Excel File!</button>
    </form>
</div>
page model ReadOnly Property () As IndexModel
	ViewData("Title") = "Home page"
End Property
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'<div class="text-center"> <h1 class="display-4"> IronXL Generate Excel File</h1> <p class="m-5"> This will be the combination @of Razor @and IronXL, together they will Export data @to Excel file.</p> <form method="post" asp-page-handler="Export"> <button class="btn btn-success p-3"> Export Excel File!</button> </form> </div>
$vbLabelText   $csharpLabel

This code will change the interface of the home page and add the export button.

How to Export CSV and Excel in Razor, Figure 8: The new interface with an export button The new interface with an export button

Now create the OnPostExport method in the index.cshtml.cs file and write the following code. This code generates a worksheet, writes column names in bold, and allows setting other styling options like font size and background color. You can think of it as a simple example of exporting data from a database to an Excel file.

public FileResult OnPostExport()
{
    // Create a new workbook with the Excel file format
    WorkBook workBook = new WorkBook(IronXL.ExcelFileFormat.XLSX);

    // Create a new worksheet in the workbook
    WorkSheet workSheet = workBook.CreateWorkSheet("data");

    // Add data and styles to the new worksheet
    workSheet["A1"].Value = "Name";
    workSheet["B1"].Value = "Email";
    workSheet["C1"].Value = "Marks";
    workSheet["D1"].Value = "Percentage";

    // Set styling for column headers
    workSheet["A1:D1"].Style.Font.Bold = true;

    // Filling the worksheet with data
    workSheet["A2"].Value = "Nick";
    workSheet["A3"].Value = "Roy";
    workSheet["A4"].Value = "Chris";
    workSheet["B2"].Value = "Nick@gmail.com";
    workSheet["B3"].Value = "Roy123@gmail.com";
    workSheet["B4"].Value = "Chris1999@gmail.com";
    workSheet["C2"].Value = "850";
    workSheet["C3"].Value = "710";
    workSheet["C4"].Value = "990";
    workSheet["D2"].Value = "85%";
    workSheet["D3"].Value = "71%";
    workSheet["D4"].Value = "99%";

    // Return the file as an Excel sheet
    return File(workBook.ToStream().ToArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Exported.xlsx");
}
public FileResult OnPostExport()
{
    // Create a new workbook with the Excel file format
    WorkBook workBook = new WorkBook(IronXL.ExcelFileFormat.XLSX);

    // Create a new worksheet in the workbook
    WorkSheet workSheet = workBook.CreateWorkSheet("data");

    // Add data and styles to the new worksheet
    workSheet["A1"].Value = "Name";
    workSheet["B1"].Value = "Email";
    workSheet["C1"].Value = "Marks";
    workSheet["D1"].Value = "Percentage";

    // Set styling for column headers
    workSheet["A1:D1"].Style.Font.Bold = true;

    // Filling the worksheet with data
    workSheet["A2"].Value = "Nick";
    workSheet["A3"].Value = "Roy";
    workSheet["A4"].Value = "Chris";
    workSheet["B2"].Value = "Nick@gmail.com";
    workSheet["B3"].Value = "Roy123@gmail.com";
    workSheet["B4"].Value = "Chris1999@gmail.com";
    workSheet["C2"].Value = "850";
    workSheet["C3"].Value = "710";
    workSheet["C4"].Value = "990";
    workSheet["D2"].Value = "85%";
    workSheet["D3"].Value = "71%";
    workSheet["D4"].Value = "99%";

    // Return the file as an Excel sheet
    return File(workBook.ToStream().ToArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Exported.xlsx");
}
Public Function OnPostExport() As FileResult
	' Create a new workbook with the Excel file format
	Dim workBook As New WorkBook(IronXL.ExcelFileFormat.XLSX)

	' Create a new worksheet in the workbook
	Dim workSheet As WorkSheet = workBook.CreateWorkSheet("data")

	' Add data and styles to the new worksheet
	workSheet("A1").Value = "Name"
	workSheet("B1").Value = "Email"
	workSheet("C1").Value = "Marks"
	workSheet("D1").Value = "Percentage"

	' Set styling for column headers
	workSheet("A1:D1").Style.Font.Bold = True

	' Filling the worksheet with data
	workSheet("A2").Value = "Nick"
	workSheet("A3").Value = "Roy"
	workSheet("A4").Value = "Chris"
	workSheet("B2").Value = "Nick@gmail.com"
	workSheet("B3").Value = "Roy123@gmail.com"
	workSheet("B4").Value = "Chris1999@gmail.com"
	workSheet("C2").Value = "850"
	workSheet("C3").Value = "710"
	workSheet("C4").Value = "990"
	workSheet("D2").Value = "85%"
	workSheet("D3").Value = "71%"
	workSheet("D4").Value = "99%"

	' Return the file as an Excel sheet
	Return File(workBook.ToStream().ToArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Exported.xlsx")
End Function
$vbLabelText   $csharpLabel

This above code will create a workbook and return the file as an Excel sheet. This method is linked to the button, and once the button is clicked, it will automatically create and download the XLSX exported file.

How to Export CSV and Excel in Razor, Figure 9: Export an XLSX file in the browser Export an XLSX file in the browser

How to Export CSV and Excel in Razor, Figure 10: The data in the exported XLSX file The data in the exported XLSX file

6. Export Data to CSV File

You can easily export CSV text files with one change in the above code. Just replace the return file code with the following, and your Razor page will return a CSV file.

return File(workBook.ToStream().ToArray(), "text/csv", "Student.csv");
return File(workBook.ToStream().ToArray(), "text/csv", "Student.csv");
Return File(workBook.ToStream().ToArray(), "text/csv", "Student.csv")
$vbLabelText   $csharpLabel

How to Export CSV and Excel in Razor, Figure 11: Export a CSV file in the browser Export a CSV file in the browser

How to Export CSV and Excel in Razor, Figure 12: The data in the exported CSV file The data in the exported CSV file

7. Conclusion

Exporting data to Excel sheets and CSV files is a common task in web development, and Razor and IronXL make it easy to accomplish. With IronXL, developers can easily create Excel spreadsheets and save them to a file or stream. Razor can then be used to generate dynamic content that includes links to the Excel document, allowing users to download them directly from the web page. This makes it simple to create reports and other data-driven content that can be easily shared with others.

The combination of Razor and IronXL .NET Core Razor Pages provides a powerful toolset for web developers looking to create dynamic, data-driven web pages. To start using Razor and IronXL, one needs to have Visual Studio and .NET Core SDK installed. After that, creating a new Visual Studio project and installing the IronXL library can be done easily. Finally, by changing the interface of the home page and creating an OnPostExport method, developers can export data to Excel documents in a few simple steps.

To learn more about IronXL, Razor and how to export data to Excel and CSV files, please visit the following page.

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.

Users can also benefit from Iron Suite, a Suite of 5 professional ASP.NET Core libraries including IronXL, IronPDF, and more.

常见问题解答

如何使用 Razor Pages 将数据导出到 Excel?

您可以将 IronXL 与 Razor Pages 结合使用,以将数据导出到 Excel。首先通过 NuGet 包管理器或 Visual Studio 命令行安装 IronXL。然后,创建一个新的工作簿和工作表,用数据填充,然后使用 Razor 导出为 Excel 文件。

设置使用 Razor 导出数据到 Excel 的环境需要哪些步骤?

要设置您的环境,您需要 Visual Studio 和 .NET Core SDK。创建一个新的 ASP.NET Core Web App 项目,从 NuGet 安装 IronXL,并修改 Razor 界面以添加导出功能。

在 .NET 应用程序中将数据导出到 CSV 文件的过程是什么?

要使用 IronXL 将数据导出为 CSV 文件,修改您的 Razor Page 代码以 'text/csv' 格式返回文件。这涉及使用 IronXL 处理工作表数据并指定 CSV 作为输出格式。

从 Razor Pages 导出时可以给 Excel 电子表格进行样式设置吗?

可以,IronXL 允许您在从 Razor Pages 导出时为 Excel 电子表格应用样式。您可以自定义字体、颜色和其他格式元素,以提高数据的展示效果。

IronXL 可用于非商业项目吗?

IronXL 可免费用于非商业开发目的。您还可以在生产环境中使用免费试用版进行测试,详细的商业使用定价计划也可获得。

IronXL 如何简化涉及 Excel 和 CSV 文件的 Web 开发任务?

IronXL 通过提供一个强大的 API 直接从 Razor Pages 生成和操作 Excel 和 CSV 文件,简化了 Web 开发。它消除了对 Interop 的需求,使数据导出任务更加高效且易于实现。

为什么开发人员会选择 Razor 和 IronXL 来执行数据导出任务?

开发人员因其易用性、灵活性和强大的功能而选择 Razor 和 IronXL。它们支持将数据导出功能无缝集成到 Web 应用程序中,从而允许创建可轻松共享的动态数据驱动内容。

Curtis Chau
技术作家

Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。

除了开发之外,Curtis 对物联网 (IoT) 有浓厚的兴趣,探索将硬件和软件集成的新方法。在空闲时间,他喜欢玩游戏和构建 Discord 机器人,将他对技术的热爱与创造力相结合。