How to Use C# to Convert Datatable to CSV
Convert a DataTable to CSV in C# using IronXL by creating a WorkBook, populating it with DataTable rows, and calling SaveAsCsv() method - no complex loops or Interop required.
Quickstart: One-Line Export of DataTable to CSV
Use IronXL to convert a filled DataTable into a CSV file with one method call—no loops, no Interop, no complexity. You need only a WorkBook and its DefaultWorkSheet to export in seconds using SaveAsCsv.
Get started making PDFs with NuGet now:
Install IronXL with NuGet Package Manager
Copy and run this code snippet.
IronXL.WorkBook.Create().DefaultWorkSheet.SaveAsCsv("output.csv", ",");Deploy to test on your live environment
Minimal Workflow (5 steps)
- Download and install convert DataTable to CSV C# Library
- Utilize
DataTableclass to store new data - Create new or import existing spreadsheet
- Loop through table rows and populate cells in worksheet accordingly
- Export to CSV file with
SaveAsCsvC# function
Step 1
How Do I Install IronXL in My Project?
You must install IronXL before using it in your applications. IronXL provides multiple installation options for your projects. IronXL is a library that simplifies working with Excel files in C# without requiring Microsoft Excel or Interop installation.
Which Installation Method Should I Use?
Download from the official site using the following link: https://ironsoftware.com/csharp/excel/docs/
or
- In Visual Studio, select the Project menu
- Click Manage NuGet Packages
- Search for IronXL.Excel
- Click Install
What NuGet Command Should I Use?
Install-Package IronXL.Excel
Why Choose NuGet Package Manager?
NuGet is the preferred method for .NET developers because it automatically manages dependencies and keeps libraries current. The IronXL package includes all necessary components for converting spreadsheet file types and working with various Excel formats.
How to Tutorial
How Do I Create and Export a DataTable to CSV?
The process of converting a DataTable to CSV involves creating a workbook, populating it with data, and using IronXL's built-in CSV writing functionality. This approach is more efficient than manually building CSV strings or using traditional file streaming methods.
What Namespace Do I Need to Import?
First, import the IronXL namespace. IronXL provides comprehensive support for importing and exporting DataSet and DataTable objects, making it ideal for database-driven applications.
using IronXL;using IronXL;Imports IronXLWhat's the Complete Code Example?
Add the following code:
:path=/static-assets/excel/content-code-examples/how-to/csharp-database-to-csv-datatable.csusing IronXL;
using System;
using System.Data;
// Create a new DataTable object
DataTable table = new DataTable();
// Add a single column named "Example_DataSet" of type string
table.Columns.Add("Example_DataSet", typeof(string));
// Add rows to the DataTable
table.Rows.Add("0");
table.Rows.Add("1");
table.Rows.Add("2");
table.Rows.Add("3");
table.Rows.Add("1");
table.Rows.Add("2");
table.Rows.Add("3");
// Create a new Excel workbook and set its author metadata
WorkBook wb = WorkBook.Create(ExcelFileFormat.XLS);
wb.Metadata.Author = "OJ";
// Get the default worksheet
WorkSheet ws = wb.DefaultWorkSheet;
// Initialize rowCounter for Excel sheet rows
int rowCount = 1;
// Loop through each row in the DataTable and add the data to the Excel worksheet
foreach (DataRow row in table.Rows)
{
// Populate worksheet cells with data from DataTable
ws["A" + (rowCount)].Value = row[0].ToString();
rowCount++;
}
// Save the workbook as a CSV file
wb.SaveAsCsv("Save_DataTable_CSV.csv", ";"); // Will be saved as: Save_DataTable_CSV.Sheet1.csvIRON VB CONVERTER ERROR developers@ironsoftware.comHow Does the Code Work Step by Step?
The above code creates a data table, creates a new workbook specifying 'OJ' as its owner, then uses a foreach loop to insert data from the data table into the Excel worksheet. Finally, the SaveAsCsv method exports the datatable to CSV.
The process breakdown:
DataTable Creation: Initialize a new DataTable and define its schema by adding columns. This resembles defining a database table structure.
Data Population: Add rows to the DataTable using the
Rows.Add()method. Each row represents a record for CSV export.Workbook Generation: IronXL's WorkBook.Create() method initializes a new Excel workbook. You can also create spreadsheets with multiple worksheets if needed.
Cell Population: The foreach loop iterates through DataTable rows and maps each value to a specific worksheet cell using cell reference syntax (e.g., "A1", "A2").
- CSV Export: The
SaveAsCsv()method handles CSV formatting complexities, including proper escaping of special characters and delimiter handling.
What About Advanced DataTable Scenarios?
For complex DataTables with multiple columns, extend the code like this:
// Create a DataTable with multiple columns
DataTable advancedTable = new DataTable();
advancedTable.Columns.Add("ID", typeof(int));
advancedTable.Columns.Add("Name", typeof(string));
advancedTable.Columns.Add("Price", typeof(decimal));
// Add sample data
advancedTable.Rows.Add(1, "Product A", 29.99m);
advancedTable.Rows.Add(2, "Product B", 49.99m);
advancedTable.Rows.Add(3, "Product C", 19.99m);
// Create workbook and worksheet
WorkBook workbook = WorkBook.Create();
WorkSheet worksheet = workbook.DefaultWorkSheet;
// Add headers
for (int col = 0; col < advancedTable.Columns.Count; col++)
{
worksheet[1, col + 1].Value = advancedTable.Columns[col].ColumnName;
}
// Add data rows
for (int row = 0; row < advancedTable.Rows.Count; row++)
{
for (int col = 0; col < advancedTable.Columns.Count; col++)
{
worksheet[row + 2, col + 1].Value = advancedTable.Rows[row][col];
}
}
// Save as CSV with comma delimiter
workbook.SaveAsCsv("products.csv", ",");// Create a DataTable with multiple columns
DataTable advancedTable = new DataTable();
advancedTable.Columns.Add("ID", typeof(int));
advancedTable.Columns.Add("Name", typeof(string));
advancedTable.Columns.Add("Price", typeof(decimal));
// Add sample data
advancedTable.Rows.Add(1, "Product A", 29.99m);
advancedTable.Rows.Add(2, "Product B", 49.99m);
advancedTable.Rows.Add(3, "Product C", 19.99m);
// Create workbook and worksheet
WorkBook workbook = WorkBook.Create();
WorkSheet worksheet = workbook.DefaultWorkSheet;
// Add headers
for (int col = 0; col < advancedTable.Columns.Count; col++)
{
worksheet[1, col + 1].Value = advancedTable.Columns[col].ColumnName;
}
// Add data rows
for (int row = 0; row < advancedTable.Rows.Count; row++)
{
for (int col = 0; col < advancedTable.Columns.Count; col++)
{
worksheet[row + 2, col + 1].Value = advancedTable.Rows[row][col];
}
}
// Save as CSV with comma delimiter
workbook.SaveAsCsv("products.csv", ",");IRON VB CONVERTER ERROR developers@ironsoftware.comWhat Does the Output Look Like?
The output Excel worksheet displays as follows:
How Do I Handle Large DataTables?
When working with large DataTables containing thousands of rows, IronXL maintains excellent performance. The library handles substantial datasets efficiently. For production environments, apply your license key to remove watermarks and enable full functionality.
What About Error Handling?
Always implement proper error handling when working with file operations:
try
{
// Your DataTable to CSV conversion code
WorkBook wb = WorkBook.Create();
// ... rest of the code
wb.SaveAsCsv("output.csv", ",");
Console.WriteLine("CSV file created successfully!");
}
catch (Exception ex)
{
Console.WriteLine($"Error creating CSV: {ex.Message}");
}try
{
// Your DataTable to CSV conversion code
WorkBook wb = WorkBook.Create();
// ... rest of the code
wb.SaveAsCsv("output.csv", ",");
Console.WriteLine("CSV file created successfully!");
}
catch (Exception ex)
{
Console.WriteLine($"Error creating CSV: {ex.Message}");
}IRON VB CONVERTER ERROR developers@ironsoftware.comLibrary Quick Access
IronXL API Reference Documentation
Learn more and share how to merge, unmerge, and work with cells in Excel spreadsheets using the handy IronXL API Reference Documentation.
IronXL API Reference DocumentationFrequently Asked Questions
How do I convert a DataTable to CSV in C# without writing complex loops?
IronXL provides a simple one-line solution to convert DataTable to CSV. After creating a WorkBook and populating it with your DataTable data, you can use the SaveAsCsv() method to export directly to CSV format without writing loops or using Interop.
What are the installation options for the DataTable to CSV conversion library?
IronXL can be installed via NuGet Package Manager in Visual Studio by searching for 'IronXL.Excel' or using the NuGet command line. This is the preferred method as it automatically manages dependencies and keeps the library current.
Do I need Microsoft Excel installed to convert DataTable to CSV?
No, IronXL works independently without requiring Microsoft Excel or Interop installation. It's a standalone library that simplifies working with Excel files and CSV exports in C# applications.
What namespace do I need to import for DataTable to CSV conversion?
You need to import the IronXL namespace by adding 'using IronXL;' at the top of your C# file. This provides access to comprehensive support for importing and exporting DataSet and DataTable objects.
Can I specify a custom delimiter when exporting to CSV?
Yes, IronXL's SaveAsCsv() method allows you to specify a custom delimiter. In the example code, a comma (",") is used as the delimiter, but you can change this to any character that suits your requirements.








