USING IRONXL

How to Export Datatable to CSV in C#

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.

IronXL Library Features

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 of the .NET Frameworks, including the Console, Windows Forms, and Web, are supported by IronXL.
  • IronXL operates on a variety of operating systems, including Windows, Linux, and macOS.
  • IronXL makes it simple and quick to read Excel files.
  • IronXL supports reading different Excel file formats including XLSX files, XLS, CSV, TSV, XLST, XLSM files, and more. We can also load, modify, export Datatables, export datasets, and more.
  • IronXL can export and save files with a wide range of suffixes, including XLS, CSV, TSV, JSON, and others.
  • IronXL can generate Excel calculations.
  • IronXL supports a variety of Excel column data formats, including text, numbers, formulas, dates, currencies, and percentages.

For more details visit here.

1. Creating 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-like application or different project templates. To keep things simple, this lesson will use the Console Application.

How to Export DataTable to CSV in C#, Figure 1: Create a new project in Visual Studio Create a new project in Visual Studio

After that, input the project's name and location.

How to Export DataTable to CSV in C#, Figure 2: Configure the new project Configure the new project

Select the following structure next. .NET Core 6 will be used in this undertaking.

How to Export Datatable to CSV in C#, Figure 3: Select a .NET Framework version 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.

How to Export Datatable to CSV in C#, Figure 4: The newly created Console Application project The newly created Console Application project

The library can then be added and used to evaluate the code.

2. 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

Installing IronXL using Visual Studio

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.

How to Export Datatable to CSV in C#, Figure 5: Navigate to NuGet Package Manager Navigate to NuGet Package Manager

How to Export Datatable to CSV in C#, Figure 6: Install IronXL package in NuGet Package Manager UI Install IronXL package in NuGet Package Manager UI

Installing IronXL using the Visual Studio NuGet Package Manager Console

Many individuals enjoy 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
    Install-Package IronXL.Excel
    SHELL
  • Wait for IronXL to be downloaded and installed into the active project.

How to Export Datatable to CSV in C#, Figure 7: Install the IronXL package in Package Manager Console UI Install the IronXL package in Package Manager Console UI

Downloading IronXL Directly from the NuGet Website

The NuGet package can be downloaded straight from the website as a third option.

  • Explore the official NuGet link.
  • The download package choice 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.

Getting 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.

3. Export to CSV File

DataTables can be easily and quickly created to CSV files using IronXL. It helps write data into a new CSV file.

First, as shown in the code image below, the IronXL namespace should be included to use the IronXL classes and methods.

How to Export Datatable to CSV in C#, Figure 8: Add common namespaces Add common namespaces

Excel files can be created using IronXL, which then transforms them into WorkBook objects. Then conduct a variety of operations on them after turning them into 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, ";");
}
Imports IronXL
Imports System.Data

' Entry point of the application
Shared Sub Main(ByVal args() As String)
	' Specify the file path for the CSV file output
	ExportToExcel("H:\test.csv")
End Sub

' Exports the DataTable to an Excel file and saves it as CSV
Public Shared Sub ExportToExcel(ByVal filepath As String)
	' Create a DataTable and add columns and rows
	Dim table As New DataTable()
	table.Columns.Add("DataSet_Fruits", GetType(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
	Dim wb As WorkBook = WorkBook.Create(ExcelFileFormat.XLS)
	Dim writer = wb.DefaultWorkSheet
	Dim rowCount As Integer = 1
	For Each row As DataRow In table.Rows
		' Write each item from the DataTable into the worksheet starting from cell A1
		writer("A" & (rowCount)).Value = row(0).ToString()
		rowCount += 1
	Next row
	' Save the workbook as a CSV file with a specified delimiter
	wb.SaveAsCsv(filepath, ";")
End Sub
$vbLabelText   $csharpLabel

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 the values have been added to the worksheet, the SaveAsCsv method is used to save them into a CSV file; at the same time, we can also give the delimiter and file name with location as parameters.

How to Export Datatable to CSV in C#, Figure 9: The output CSV file 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.

To learn more about the IronXL tutorial click on this how-to export to Excel formats.

Conclusion

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.

IronXL's starting price at launch is $749. 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

What is this software library?

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.

What spreadsheet formats does this library support?

IronXL supports reading different Excel file formats including XLSX files, XLS, CSV, TSV, XLST, XLSM files, and more.

Does this library require Microsoft Excel to be installed?

No, IronXL does not require Microsoft Excel to be installed as it is a standalone .NET software library.

How can this library be installed?

IronXL can be installed via Visual Studio, using the Visual Studio Package Manager Console, downloading directly from the NuGet website, or downloading directly from the IronXL website.

Can this library be used on different operating systems?

Yes, IronXL operates on a variety of operating systems, including Windows, Linux, and macOS.

What are the main features of this library?

IronXL provides an all-in-one solution for Excel document-related tasks, including reading and writing CSV files, performing formula calculations, string or number sorting, trimming and appending, and more.

Is this library compatible with .NET Core and .NET Framework?

Yes, IronXL is fully compatible with .NET Core, .NET Framework, Xamarin, Mobile, Linux, macOS, and Azure.

How does this library handle CSV file export?

IronXL allows for the creation of DataTables that can be easily and quickly exported to CSV files, providing methods to write data into a new CSV file.

What is the starting price of this library?

IronXL's starting price at launch is listed as $liteLicense, with additional options for one-year subscription fees for product assistance and updates.

Regan Pun
Software Engineer
Regan graduated from the University of Reading, with a BA in Electronic Engineering. Before joining Iron Software, his previous job roles had him laser-focused on single tasks; and what he most enjoys at Iron Software is the spectrum of work he gets to undertake, whether it’s adding value to sales, technical support, product development or marketing. He enjoys understanding the way developers are using the Iron Software library, and using that knowledge to continually improve documentation and develop the products.
< PREVIOUS
How to Get Cell Value From Excel File in C#
NEXT >
How to Import Excel File in C#