How to Export CSV and Excel in Razor

Looking for a way to export data to an Excel file using Razor Page?

What is Razor? Razor is a web framework used for creating dynamic web pages in .NET applications. It allows developers to create server-side HTML files with embedded C# or VB code, making it easy to write code that generates dynamic content. Razor was introduced in 2011 and has since become a popular web development tool due to its simplicity and flexibility.

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. CSV file format can also be generated using IronXL and downloaded using Razor in a similar manner. 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 .NET Core SDK installed on your computer. You can download the latest version of .NET Core SDK from the official Microsoft website.
  3. Your Web Development environment must be set before we start working with Razor view.

3. Creating 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.

  3. Select the type of project you want to create, because we will be using Razor page we will select ASP.NET Core Web App and click on Next.

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

  5. Now in the new window select your target Framework, and 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, we can 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. Once the installation is complete, our project will be set up to use the IronXL library.

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

IronXL in search results:

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: Install-Package IronXL.Excel

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

5. Export Data to Excel File in Razor Net Core

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

We need to change the above interface by editing index.cshtml file in 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 and togather 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 and togather 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 @and togather 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>
VB   C#

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

Now create the onPostExport method in index.cshtml.cs file and write the following code. This code is generating a worksheet and writing column names as bold. Users can also set the font size and even set the background color of the columns using style. It is the same as exporting database table data from SQL server or any other database server to Excel.

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 = "Name";
    workSheet["B1"].Value = "Email";
    workSheet["C1"].Value = "Marks";
    workSheet["D1"].Value = "Persent Age";
    workSheet["A1:D1"].Style.Font.Bold = true;
    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 File(workBook.ToStream().ToArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Exported.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 = "Name";
    workSheet["B1"].Value = "Email";
    workSheet["C1"].Value = "Marks";
    workSheet["D1"].Value = "Persent Age";
    workSheet["A1:D1"].Style.Font.Bold = true;
    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 File(workBook.ToStream().ToArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Exported.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 = "Name"
	workSheet("B1").Value = "Email"
	workSheet("C1").Value = "Marks"
	workSheet("D1").Value = "Persent Age"
	workSheet("A1:D1").Style.Font.Bold = True
	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 File(workBook.ToStream().ToArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Exported.xlsx")
End Function
VB   C#

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

6. Export Data to CSV File

Same as above you can easily export csv text files with change in single line of code in above code samples. Just replace the return file code in the above source code with this 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")
VB   C#

7. Conclusion

Exporting data to Excel sheet 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. In order 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 file please visit the following page.

IronXL is free to use for non-commerical development purposes. A 30-day 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.