The brief tutorial will guide you on how to export list data to Excel in C#. The List is one of the most common constructs in a programming language to hold data that can be further exported to Excel. This is the main concept which you will learn here that how using C# create Excel file from list and store it on disk in XLSX format.
Steps to Export List Data to Excel in C#
- Install Aspose.Cells library using Nuget package manager to export list data to Excel
- Create Workbook class object to hold data exported from a list
- Create a list to store target data for exporting to Excel
- Fill the list with sample data or fill it from some external source
- Get a reference to a particular workbook sheet where exported data will be saved
- Call the ImportArrayList function to export list data to Excel
- Save the output Excel file containing the exported data from a list
Here in the above steps, a simple approach is followed where first a workbook class object is created along with accessing a reference to a particular sheet for saving the list data. The list is filled manually however, it can be filled from some external source also like fetching data from some database, Web API, or from some other network resource. Finally, using C# write list to Excel and save the output file on the disk.
Code to Export List to Excel in C#
This code uses a Workbook and Worksheet class object to access the control of the file for writing list to Excel using C#. The ImportArrayList function of Worksheet.Cells class is used that requires source list reference, the first row and column in the worksheet where data is to be placed and direction of data i.e. either store data in a vertical column or in a horizontal row.
In this tutorial, we learned to write list data to Excel in C# however if you want to export DataTable to Excel, you may refer to the article on how to convert DataTable to Excel in C#.