Read CSV File into Data Table


Hello everyone, in general development projects the most common requirement of client is reading different types of files and process its data in the project. Today we will learn how to read the csv file and get its data into data table. In the csv file the data is saved with Comma separated (,) format.

Code playground

Let’s start with code. We will make a new Windows application using C#.

Step 1

Open Visual Studio. Select New Project option, then console application template.

Step 2

I am using Visual Studio 2022 community version for this project.

Step 3

Name it as you want. I have name this application “ReadCSVFileApp”.

Step 4

Now, add Reference of the csv library - IronXL.

Step 5

Right click on the Solution in the solution explorer and click “Manage NuGet packages” option.

Step 6

Browse tab type “IronXL.Excel” keyword, following screen will appear.

IronXL NuGet Package

Step 7

Click the install button. Visual Studio will prompt you that it is installing following components and it related libraries (dependencies) in this project.

Step 8

Click on OK. The NuGet package will be installed.

IronXL NuGet package

Step 9

Now we a sample csv file in project folder. This file’s data will be read by us.


Step 10

Now add the following logic.

using IronXL;
using System.Data;

string filepath = Environment.CurrentDirectory;
var MainDirectory = filepath.Split(new string[] { "bin" }, StringSplitOptions.None)[0];
WorkBook workbook = WorkBook.LoadCSV(MainDirectory + "/SampleCSVFile.csv", fileFormat: ExcelFileFormat.XLSX, ListDelimiter: ",");
WorkSheet ws = workbook.DefaultWorkSheet;

Step 11

Let’s discuss this code. First, we will get the csv file path from our project.

Step 12

After getting the file path use LoadCSV function of NuGet package. This function will return the WorkBook object.

Step 13

Now to further process this object we can convert it into data table.

//Convert the worksheet to System.Data.DataTable
//Boolean parameter sets the first row as column names of your table.
DataTable dataTable = ws.ToDataTable(true);

Step 14

We can also save the fetched data directly into excel file by using following code.

workbook.SaveAs(MainDirectory + "/CsvToExcel.xlsx");


The IronXL is very helpful with its default pre-defined function in all types of development projects. It is easy to use also. Developer no need to do custom code for this type of requirement.

The code of this tutorial is attached. You can download the code, play with code and modify according to your requirement. Happy coding.