The API doesn't require a lot of introduction since it is pretty easy to understand. Like in the previous example, I add a headline row and put in the values from the users list in the following rows. Excel worksheets aren't available using a CSV file. You can see the benefits of ClosedXML in line 5 where I create a new worksheet named Users. To create the Excel document, I'm creating a new XLWorkbook. Worksheet.Cell(currentRow, 2).Value = user.Username Worksheet.Cell(currentRow, 1).Value = user.Id Worksheet.Cell(currentRow, 2).Value = "Username" Worksheet.Cell(currentRow, 1).Value = "Id" Here's the code: public IActionResult Excel() Check out their documentation for details. ClosedXML provides a rich set of features to include colors, calculations, and much more. For this post, I have formatted the output like in the CSV example for consistency. To generate an XLSX file with ClosedXML start by installing the following NuGet package: Install-Package ClosedXML I also looked at alternative packages like EPPlus and DocumentFormat.OpenXml from Microsoft, but neither provides an API as simple as ClosedXML (IMO). I have been using the ClosedXML package in the past, why I was happy to see that the package is still being developed and supported in. I wouldn't recommend doing that since the format is complex and there are a lot of good NuGet packages available. Since XLSX files are XML based, you can generate the content yourself. CSV files cannot contain colors, formulas, etc. If you need more complexity in your exported file than simple tabular data, you need to export data as a real Excel file.
#Razorsql import csv rows download#
By returning the content as a file, the browser will automatically download the content as a CSV file named users.csv. Finally, I'm returning the generated CSV using the File helper available in ASP.NET Core. Using the StringBuilder class available in the System.Text namespace, I'm adding headers in the first line and then appending a line per user. Return File((builder.ToString()), "text/csv", "users.csv") In a real application, these data would come from user input, a database, or similar: public class HomeController : Controller Let's start simple.įor the examples in this post, I'll use an ASP.NET Core controller with some hard-coded data. If you need to embed colors and formulas, you will need something more advanced. If you need simple tabular data, generating a CSV file may be sufficient. When needing to export data to Excel from ASP.NET Core, you have a couple of different options. Supporting the same in ASP.NET Core was a good excuse to look at different possibilities and write about it ? I have been implementing a lot of exporting in the past with ASP.NET and ASP.NET MVC.
I had to export some data to Excel from an ASP.NET Core website.