Read a CSV File in C#
When you need to read CSV files in C#, IronXL is an easy answer. You can read a CSV file with commas, or any other delimiter, as seen in the code segments below.
How to Read a CSV File in C#
- Download and install the C# CSV reading library
- Create a C# or VB project
- Add the code example from this page to your project
- In the code, specify the path to the CSV, and the output name & file format
- Run the C# project to view the document
Reading CSV Files in .NET Applications
Step 1
1. Install the IronXL Library
Before you can make use of IronXL to read CSV files in MVC or ASP or dotnet core, you need to install it first. Here is a quick walk-through.
- In Visual Studio, select the Project menu
- Manage NuGet Packages
- Search for IronXL.Excel
- Install
Or Download from the Iron Software website, here: https://ironsoftware.com/csharp/excel/packages/IronXL.zip
How to Tutorial
2. Read CSV Files Programmatically
Now for the project!
Add the IronXL Namespace
using IronXL;
using IronXL;
Imports IronXL
Add code to read a CSV file programmatically with IronXL and C#
/**
Read a CSV file
anchor-read-csv-files-programmatically
**/
private void button2_Click(object sender, EventArgs e)
{
WorkBook workbook = WorkBook.LoadCSV("Read_CSV_Ex.csv", fileFormat: ExcelFileFormat.XLSX, ListDelimiter: ",");
WorkSheet ws = workbook.DefaultWorkSheet;
workbook.SaveAs("Csv_To_Excel.xlsx");
}
/**
Read a CSV file
anchor-read-csv-files-programmatically
**/
private void button2_Click(object sender, EventArgs e)
{
WorkBook workbook = WorkBook.LoadCSV("Read_CSV_Ex.csv", fileFormat: ExcelFileFormat.XLSX, ListDelimiter: ",");
WorkSheet ws = workbook.DefaultWorkSheet;
workbook.SaveAs("Csv_To_Excel.xlsx");
}
'''
'''Read a CSV file
'''anchor-read-csv-files-programmatically
'''*
Private Sub button2_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim workbook As WorkBook = WorkBook.LoadCSV("Read_CSV_Ex.csv", fileFormat:= ExcelFileFormat.XLSX, ListDelimiter:= ",")
Dim ws As WorkSheet = workbook.DefaultWorkSheet
workbook.SaveAs("Csv_To_Excel.xlsx")
End Sub
A Workbook object is created. The LoadCSV
method of the Workbook object is then used to specify the name of the CSV file to be read, in format to read it into, and what the delimiter is for the file. In this case, a comma is used as a separator.
A Worksheet object is then created. This is where the contents of the CSV file will be placed. Then the file is saved under a new name and format.
Library 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 Documentation