How to Import CSV To Datatable in C#

In this tutorial, we explore the process of importing CSV files into a data table in C# using the IronXL library. We begin by ensuring that the IronXL library is installed via the NuGet package manager. The core of the process involves defining a class called CSVToDataTable with a static method, ImportCSVToDataTable. This method first checks if the specified CSV file exists, throwing a file-not-found exception if it does not. Upon confirming the file's existence, we retrieve the worksheet from the workbook and convert it to a data table using IronXL's provided methods. The data table is then returned and displayed in the console by iterating through its rows. We also implement error catching to handle any potential issues during the process. This guide not only helps in converting CSV files but also encourages exploring additional functionalities of IronXL. For further learning, viewers are encouraged to like and subscribe for more tutorials, and to explore the features of IronXL by downloading the software from the provided link.

Here's the C# code to import a CSV file into a data table using IronXL:

using System;
using System.Data;
using System.IO;
using IronXL;

namespace CSVImporter
{
    public class CSVToDataTable
    {
        // This static method imports a CSV file and returns it as a DataTable.
        public static DataTable ImportCSVToDataTable(string filePath)
        {
            // Check if the specified file exists
            if (!File.Exists(filePath))
                throw new FileNotFoundException("The CSV file could not be found.", filePath);

            try
            {
                // Load the CSV file into a workbook
                WorkBook workbook = WorkBook.LoadCSV(filePath, fileDelimeter: ',');

                // Get the first worksheet from the workbook
                WorkSheet sheet = workbook.WorkSheets[0];

                // Convert the WorkSheet to a DataTable
                DataTable dataTable = sheet.ToDataTable(true); // 'true' to include column names

                return dataTable;
            }
            catch (Exception ex)
            {
                Console.WriteLine("An error occurred while importing the CSV file: " + ex.Message);
                return null;
            }
        }

        static void Main(string[] args)
        {
            string filePath = "path/to/your/csvfile.csv";

            // Import CSV file as DataTable
            DataTable dataTable = ImportCSVToDataTable(filePath);

            if (dataTable != null)
            {
                // Iterate through the rows of the DataTable and print them to the console
                foreach (DataRow row in dataTable.Rows)
                {
                    foreach (var item in row.ItemArray)
                    {
                        Console.Write(item + "\t");
                    }
                    Console.WriteLine();
                }
            }
        }
    }
}
using System;
using System.Data;
using System.IO;
using IronXL;

namespace CSVImporter
{
    public class CSVToDataTable
    {
        // This static method imports a CSV file and returns it as a DataTable.
        public static DataTable ImportCSVToDataTable(string filePath)
        {
            // Check if the specified file exists
            if (!File.Exists(filePath))
                throw new FileNotFoundException("The CSV file could not be found.", filePath);

            try
            {
                // Load the CSV file into a workbook
                WorkBook workbook = WorkBook.LoadCSV(filePath, fileDelimeter: ',');

                // Get the first worksheet from the workbook
                WorkSheet sheet = workbook.WorkSheets[0];

                // Convert the WorkSheet to a DataTable
                DataTable dataTable = sheet.ToDataTable(true); // 'true' to include column names

                return dataTable;
            }
            catch (Exception ex)
            {
                Console.WriteLine("An error occurred while importing the CSV file: " + ex.Message);
                return null;
            }
        }

        static void Main(string[] args)
        {
            string filePath = "path/to/your/csvfile.csv";

            // Import CSV file as DataTable
            DataTable dataTable = ImportCSVToDataTable(filePath);

            if (dataTable != null)
            {
                // Iterate through the rows of the DataTable and print them to the console
                foreach (DataRow row in dataTable.Rows)
                {
                    foreach (var item in row.ItemArray)
                    {
                        Console.Write(item + "\t");
                    }
                    Console.WriteLine();
                }
            }
        }
    }
}
Imports Microsoft.VisualBasic
Imports System
Imports System.Data
Imports System.IO
Imports IronXL

Namespace CSVImporter
	Public Class CSVToDataTable
		' This static method imports a CSV file and returns it as a DataTable.
		Public Shared Function ImportCSVToDataTable(ByVal filePath As String) As DataTable
			' Check if the specified file exists
			If Not File.Exists(filePath) Then
				Throw New FileNotFoundException("The CSV file could not be found.", filePath)
			End If

			Try
				' Load the CSV file into a workbook
				Dim workbook As WorkBook = WorkBook.LoadCSV(filePath, fileDelimeter:= ","c)

				' Get the first worksheet from the workbook
				Dim sheet As WorkSheet = workbook.WorkSheets(0)

				' Convert the WorkSheet to a DataTable
				Dim dataTable As DataTable = sheet.ToDataTable(True) ' 'true' to include column names

				Return dataTable
			Catch ex As Exception
				Console.WriteLine("An error occurred while importing the CSV file: " & ex.Message)
				Return Nothing
			End Try
		End Function

		Shared Sub Main(ByVal args() As String)
			Dim filePath As String = "path/to/your/csvfile.csv"

			' Import CSV file as DataTable
			Dim dataTable As DataTable = ImportCSVToDataTable(filePath)

			If dataTable IsNot Nothing Then
				' Iterate through the rows of the DataTable and print them to the console
				For Each row As DataRow In dataTable.Rows
					For Each item In row.ItemArray
						Console.Write(item & vbTab)
					Next item
					Console.WriteLine()
				Next row
			End If
		End Sub
	End Class
End Namespace
$vbLabelText   $csharpLabel

Further Reading: How to Import CSV To Datatable in C#

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 Convert a Data Table to an Excel File
NEXT >
How to Export Data to Excel in Blazor using IronXL