How to Export `DataTable` to CSV in C#
IronXL enables seamless DataTable to CSV conversion in C# without requiring Microsoft Excel installation. This standalone .NET library provides a simple API to automatically convert DataTables to CSV files with custom structures and delimiters, making data export straightforward for developers.
IronXL is a popular library that allows developers to interact with Microsoft Excel documents in C# .NET technologies, including CSV files, without needing Microsoft Excel installed. It enables the automatic conversion of registered types to CSV files and the writing of CSV files with custom structures.
What Features Does the IronXL Library Offer?
Microsoft Excel documents can be read and converted to CSV files using the C# IronXL .NET library. IronXL is a standalone .NET software library that can read a variety of spreadsheet formats. It does not depend on Microsoft.Office.Interop.Excel or require the installation of Microsoft Excel.
With the help of the user-friendly C# API of IronXL, you can quickly read, modify, and create Excel spreadsheet files in the .NET environment. .NET Core, .NET Framework, Xamarin, Mobile, Linux, macOS, and Azure are all fully supported by IronXL.
- Leading .NET Core and .NET Framework Excel spreadsheet libraries for C# include IronXL.
- Virtually all .NET Frameworks are supported, including Console, Windows Forms, and Web Applications.
- IronXL operates on Windows, Linux, and macOS operating systems.
- IronXL makes reading Excel files simple and quick.
- IronXL supports multiple Excel formats: XLSX, XLS, CSV, TSV, XLST, and XLSM files.
- IronXL exports files to various formats including XLS, CSV, TSV, JSON, and XML.
- IronXL generates Excel calculations and supports formulas.
- IronXL supports Excel column data formats including text, numbers, dates, currencies, and percentages.
For more details visit the IronXL documentation overview.
How Do I Create a New Project in Visual Studio?
In Visual Studio, a .NET project must be created before the IronXL framework can be used. Any edition of Visual Studio will work, but the most recent one is advised. Depending on your needs, you can build a Windows Forms application or different project templates. To keep things simple, this tutorial will use the Console Application.
Create a new project in Visual Studio
After that, input the project's name and location.
Configure the new project
Next, select the following structure. .NET Core 6 will be used in this project.
Select a .NET Framework version
The program.cs file will be opened after the application generates the solution so that you can enter the program code and build/run the application.
The newly created Console Application project
The library can then be added and used to evaluate the code. For other project types like .NET MAUI applications or VB.NET projects, the process is similar but with framework-specific considerations.
How Do I Install the IronXL Library?
There are four methods to download and install the IronXL Library.
Which are:
- Installing via Visual Studio
- Installing using the Visual Studio Package Manager Console
- Downloading directly from the NuGet website
- Downloading directly from the IronXL website
Which Method Should I Use for Visual Studio Installation?
Using NuGet Package Manager, the IronXL module can be installed. To find IronXL, you must first launch the NuGet Package Manager and then look in the browse pane. Install IronXL by choosing it from the search listings. After that, the IronXL library will be able to use this app.
The image below demonstrates how to launch Visual Studio's NuGet Package Manager.
Navigate to NuGet Package Manager
Install IronXL package in NuGet Package Manager UI
When Should I Use the Package Manager Console?
Many developers prefer using a console to carry out tasks. So, a terminal installation is also an option. To install IronXL using the command line, adhere to the instructions below.
- Navigate to Tools > NuGet Package Manager > Package Manager interface in Visual Studio.
Input the following command into the console tab of the package manager:
Install-Package IronXL.Excel
- Wait for IronXL to be downloaded and installed into the active project.
Install the IronXL package in Package Manager Console UI
Why Would I Download from the NuGet Website?
The NuGet package can be downloaded straight from the website as a third option. This method is particularly useful when working in environments with restricted internet access or when you need to manage packages manually.
- Navigate to the official NuGet link.
- The download package option can be found in the menu on the right.
- Click the saved file twice. It will immediately be installed.
- Reload the solution after that and begin utilizing it in the project.
How Do I Install Directly from the IronXL Website?
To download the most recent package straight from the website, click this link to download an IronXL ZIP file. This link will download a ZIP file containing the latest version of the IronXL library DLL. Once the download finishes, extract the contents of the ZIP file to any directory of your choosing.
To add the file to the project after downloading, adhere to the steps listed below.
- From the solution window, right-click the project.
- Select References, and then navigate to the extracted folder containing the IronXL DLLs.
- Select the DLL, and click OK to add it to the active project as a Reference.
For deployment scenarios, you can also set up IronXL in Docker containers or deploy to cloud platforms like AWS Lambda and Azure Functions.
How Do I Export a DataTable to CSV File?
DataTables can be easily and quickly exported to CSV files using IronXL. It helps write data to new CSV files with support for custom delimiters and encoding options.
First, as shown in the code image below, the IronXL namespace should be included to use the IronXL classes and methods.
Add common namespaces
Excel files can be created using IronXL, which then transforms them into WorkBook objects. Then perform various operations on these objects. The sample code below will build an Excel file by converting a DataTable into an Excel worksheet.
using IronXL;
using System.Data;
// Entry point of the application
static void Main(string[] args)
{
// Specify the file path for the CSV file output
ExportToExcel("H:\\test.csv");
}
// Exports the DataTable to an Excel file and saves it as CSV
public static void ExportToExcel(string filepath)
{
// Create a DataTable and add columns and rows
DataTable table = new DataTable();
table.Columns.Add("DataSet_Fruits", typeof(string));
table.Rows.Add("Apple");
table.Rows.Add("Orange");
table.Rows.Add("Strawberry");
table.Rows.Add("Grapes");
table.Rows.Add("Watermelon");
table.Rows.Add("Bananas");
table.Rows.Add("Lemons");
// Create a new WorkBook and add the DataTable data to it
WorkBook wb = WorkBook.Create(ExcelFileFormat.XLS);
var writer = wb.DefaultWorkSheet;
int rowCount = 1;
foreach (DataRow row in table.Rows)
{
// Write each item from the DataTable into the worksheet starting from cell A1
writer["A" + (rowCount)].Value = row[0].ToString();
rowCount++;
}
// Save the workbook as a CSV file with a specified delimiter
wb.SaveAsCsv(filepath, ";");
}using IronXL;
using System.Data;
// Entry point of the application
static void Main(string[] args)
{
// Specify the file path for the CSV file output
ExportToExcel("H:\\test.csv");
}
// Exports the DataTable to an Excel file and saves it as CSV
public static void ExportToExcel(string filepath)
{
// Create a DataTable and add columns and rows
DataTable table = new DataTable();
table.Columns.Add("DataSet_Fruits", typeof(string));
table.Rows.Add("Apple");
table.Rows.Add("Orange");
table.Rows.Add("Strawberry");
table.Rows.Add("Grapes");
table.Rows.Add("Watermelon");
table.Rows.Add("Bananas");
table.Rows.Add("Lemons");
// Create a new WorkBook and add the DataTable data to it
WorkBook wb = WorkBook.Create(ExcelFileFormat.XLS);
var writer = wb.DefaultWorkSheet;
int rowCount = 1;
foreach (DataRow row in table.Rows)
{
// Write each item from the DataTable into the worksheet starting from cell A1
writer["A" + (rowCount)].Value = row[0].ToString();
rowCount++;
}
// Save the workbook as a CSV file with a specified delimiter
wb.SaveAsCsv(filepath, ";");
}The above code exports the DataTable to an Excel file. Column headings are created once a DataTable is created. Then, add the rows one at a time after establishing the first column. The WorkBook object is created after adding the columns and rows to the DataTable object to hold those data. The WorkSheet object is then constructed, which is added to the WorkBook object.
Each value from the DataTable is read and added using a foreach loop before adding the value to the WorkSheet. After all values have been added to the worksheet, the SaveAsCsv method saves them to a CSV file. You can specify both the delimiter and file location as parameters.
For more complex scenarios, you might want to export multiple DataTables as different worksheets or work with DataSets for more structured data organization.
Working with Different CSV Formats
IronXL provides flexibility when working with CSV files. Here's an example showing how to export a DataTable with custom formatting and encoding:
// Export with custom delimiter and encoding
public static void ExportToCSVWithOptions(DataTable dataTable, string filepath)
{
// Create workbook from DataTable
WorkBook wb = WorkBook.Create(ExcelFileFormat.XLSX);
WorkSheet ws = wb.CreateWorkSheet("DataExport");
// Add headers
for (int i = 0; i < dataTable.Columns.Count; i++)
{
ws[$"{(char)('A' + i)}1"].Value = dataTable.Columns[i].ColumnName;
}
// Add data rows
for (int row = 0; row < dataTable.Rows.Count; row++)
{
for (int col = 0; col < dataTable.Columns.Count; col++)
{
ws[$"{(char)('A' + col)}{row + 2}"].Value = dataTable.Rows[row][col];
}
}
// Save with custom delimiter (comma) and UTF-8 encoding
wb.SaveAsCsv(filepath, ",", System.Text.Encoding.UTF8);
}// Export with custom delimiter and encoding
public static void ExportToCSVWithOptions(DataTable dataTable, string filepath)
{
// Create workbook from DataTable
WorkBook wb = WorkBook.Create(ExcelFileFormat.XLSX);
WorkSheet ws = wb.CreateWorkSheet("DataExport");
// Add headers
for (int i = 0; i < dataTable.Columns.Count; i++)
{
ws[$"{(char)('A' + i)}1"].Value = dataTable.Columns[i].ColumnName;
}
// Add data rows
for (int row = 0; row < dataTable.Rows.Count; row++)
{
for (int col = 0; col < dataTable.Columns.Count; col++)
{
ws[$"{(char)('A' + col)}{row + 2}"].Value = dataTable.Rows[row][col];
}
}
// Save with custom delimiter (comma) and UTF-8 encoding
wb.SaveAsCsv(filepath, ",", System.Text.Encoding.UTF8);
}This approach gives you more control over the export process, allowing you to set cell data formats and customize the output structure.
The output CSV file
The output of the run code sample is shown above. In the screenshot, each piece of data from the data table has been individually added to the newly formed Excel sheet. You can also apply formatting to cells before exporting or add formulas for calculated values.
For more advanced CSV operations, you can:
- Read CSV files with custom delimiters
- Write to CSV files with specific encoding
- Convert between different spreadsheet formats
- Export to JSON or XML formats
To learn more about the IronXL tutorial click on this how-to export to Excel formats.
Why Should I Use IronXL for CSV Export?
One of the most popular Excel tools is IronXL. It doesn't rely on any other libraries from outside sources. It is autonomous and does not require the installation of Microsoft Excel. It operates across numerous channels.
IronXL provides an all-in-one solution for all Microsoft Excel document-related tasks to be implemented programmatically. You can perform formula calculation, string or number sorting, trimming and appending, find and replace, merge and unmerge, save files etc. You can also set cell data formats along with validate spreadsheet data. It also supports reading and writing CSV files and helps you to work like Excel data.
Additional benefits include:
- Password protection for sensitive data exports
- Performance optimization for large datasets
- Support for conditional formatting in Excel before CSV export
- Named ranges and named tables support
- Hyperlink preservation in supported formats
IronXL's starting price at launch is $799. It also offers users the choice of paying a one-year subscription fee for product assistance and updates. For an additional fee, IronXL offers security for unrestricted redistribution. To research greater approximate pricing information, please visit this licensing page.
Frequently Asked Questions
How can I export a DataTable to a CSV file in C#?
You can use IronXL to export a DataTable to a CSV file by creating a WorkBook and exporting the data into worksheet objects. This allows for seamless conversion and export without requiring Microsoft Excel.
What file formats can I export using this library?
IronXL allows exporting data into various formats such as XLS, CSV, TSV, and JSON, providing flexibility in handling different data needs.
Is it possible to perform Excel-like operations with this library?
Yes, IronXL enables Excel-like operations such as formula calculations, data sorting, and file saving, making it a comprehensive tool for Excel-related programming tasks.
Do I need to install Microsoft Excel to use this library?
No, IronXL is a standalone .NET library that does not require Microsoft Excel to be installed, allowing developers to work with Excel documents directly within their C# applications.
What platforms are compatible with this library?
IronXL is compatible with multiple platforms, including .NET Core, .NET Framework, Xamarin, as well as operating systems like Windows, Linux, and macOS.
How can I install the IronXL library in my project?
IronXL can be installed in a .NET project using Visual Studio by accessing the NuGet Package Manager or downloading directly from the NuGet or IronXL websites.
What are the pricing options available for this library?
IronXL offers a starting price with options for a one-year subscription that includes product assistance and updates, providing ongoing support and access to the latest features.









