跳至页脚内容
使用 IRONXL

使用 C# 读取 CSV 文件(代码示例教程)

This tutorial demonstrates how to read a CSV file using the IronXL C# library without installing additional interop, in a highly efficient and effective manner.

How to read CSV Files in C#

You must first install IronXL before using it to read CSV files in MVC, ASP.NET, or .NET Core. Here's a basic rundown of the process.

Select the Project menu in Visual Studio, Manage NuGet Packages, and Search for IronXL.Excel, and Install.

Read CSV File Using C# (Code Example Tutorial), Figure 1: Install the IronXL package in the NuGet Package Manager Install the IronXL package in the NuGet Package Manager

IronXL is a great tool to use when you need to read CSV files in C#. The code example below shows that you can read a CSV file using commas or another delimiter.

// Load a CSV file into a WorkBook object specifying file format and delimiters
WorkBook workbook = WorkBook.LoadCSV("Weather.csv", fileFormat: ExcelFileFormat.XLSX, ListDelimiter: ",");

// Get the default worksheet from the workbook
WorkSheet ws = workbook.DefaultWorkSheet;

// Save the workbook as an Excel file
workbook.SaveAs("Csv_To_Excel.xlsx");
// Load a CSV file into a WorkBook object specifying file format and delimiters
WorkBook workbook = WorkBook.LoadCSV("Weather.csv", fileFormat: ExcelFileFormat.XLSX, ListDelimiter: ",");

// Get the default worksheet from the workbook
WorkSheet ws = workbook.DefaultWorkSheet;

// Save the workbook as an Excel file
workbook.SaveAs("Csv_To_Excel.xlsx");
' Load a CSV file into a WorkBook object specifying file format and delimiters
Dim workbook As WorkBook = WorkBook.LoadCSV("Weather.csv", fileFormat:= ExcelFileFormat.XLSX, ListDelimiter:= ",")

' Get the default worksheet from the workbook
Dim ws As WorkSheet = workbook.DefaultWorkSheet

' Save the workbook as an Excel file
workbook.SaveAs("Csv_To_Excel.xlsx")
$vbLabelText   $csharpLabel

Read CSV File Using C# (Code Example Tutorial), Figure 2: CSV data for this tutorial CSV data for this tutorial

The object WorkBook is created. The WorkBook object's LoadCSV method is then used to indicate the name of the CSV file, its format, and the delimiters used in the CSV file being read, which are stored as a string array. Commas are utilized as delimiters in this scenario.

After that, a WorkSheet object is created; this is where the CSV file contents will be stored. The file is then renamed and stored in a new format. The CSV file data is then arranged in the worksheet in a tabular form. The output will look something like this:

Read CSV File Using C# (Code Example Tutorial), Figure 3: Data converted into Excel file Data converted into Excel file

CSV parsing in C# .NET

CSVs have several issues with how line breaks are handled in fields, and how fields might be enclosed in quotes, which prevents a simple string-split technique from working Split("'"). Instead, IronXL offers to customize delimiter using optional parameter from LoadCSV method, check the API documentation of LoadCSV for more details.

C# Records — Reading CSV Data

In the example below, the foreach loop is used to iterate over the rows in the CSV file, and the Console is used to write the data in a record.

// Load a CSV file into a WorkBook object specifying file format and delimiters
WorkBook workbook = WorkBook.LoadCSV("Weather.csv", fileFormat: ExcelFileFormat.XLSX, ListDelimiter: ",");

// Get the default worksheet from the workbook
WorkSheet ws = workbook.DefaultWorkSheet;

// Convert the worksheet data into a DataTable
DataTable dt = ws.ToDataTable(true); // The argument true indicates the first row is header

// Iterate through each row in the DataTable
foreach (DataRow row in dt.Rows)
{
    // Iterate through each column in the current row
    for (int i = 0; i < dt.Columns.Count; i++)
    {
        // Output each cell value to the console
        Console.Write(row[i] + "  ");
    }
    // New line after each row
    Console.WriteLine();
}
// Load a CSV file into a WorkBook object specifying file format and delimiters
WorkBook workbook = WorkBook.LoadCSV("Weather.csv", fileFormat: ExcelFileFormat.XLSX, ListDelimiter: ",");

// Get the default worksheet from the workbook
WorkSheet ws = workbook.DefaultWorkSheet;

// Convert the worksheet data into a DataTable
DataTable dt = ws.ToDataTable(true); // The argument true indicates the first row is header

// Iterate through each row in the DataTable
foreach (DataRow row in dt.Rows)
{
    // Iterate through each column in the current row
    for (int i = 0; i < dt.Columns.Count; i++)
    {
        // Output each cell value to the console
        Console.Write(row[i] + "  ");
    }
    // New line after each row
    Console.WriteLine();
}
' Load a CSV file into a WorkBook object specifying file format and delimiters
Dim workbook As WorkBook = WorkBook.LoadCSV("Weather.csv", fileFormat:= ExcelFileFormat.XLSX, ListDelimiter:= ",")

' Get the default worksheet from the workbook
Dim ws As WorkSheet = workbook.DefaultWorkSheet

' Convert the worksheet data into a DataTable
Dim dt As DataTable = ws.ToDataTable(True) ' The argument true indicates the first row is header

' Iterate through each row in the DataTable
For Each row As DataRow In dt.Rows
	' Iterate through each column in the current row
	For i As Integer = 0 To dt.Columns.Count - 1
		' Output each cell value to the console
		Console.Write(row(i) & "  ")
	Next i
	' New line after each row
	Console.WriteLine()
Next row
$vbLabelText   $csharpLabel

Read CSV File Using C# (Code Example Tutorial), Figure 4: Accessing data from CSV file and display into the Console Accessing data from CSV file and display into the Console

Converting a CSV File string line to Excel Format

The procedure is straightforward: loading a CSV file and saving it as an Excel file.

// Load a CSV file into a WorkBook object specifying file format and delimiters
WorkBook workbook = WorkBook.LoadCSV("test.csv", fileFormat: ExcelFileFormat.XLSX, ListDelimiter: ",");

// Get the default worksheet from the workbook
WorkSheet ws = workbook.DefaultWorkSheet;

// Save the workbook as an Excel file
workbook.SaveAs("CsvToExcelConversion.xlsx");
// Load a CSV file into a WorkBook object specifying file format and delimiters
WorkBook workbook = WorkBook.LoadCSV("test.csv", fileFormat: ExcelFileFormat.XLSX, ListDelimiter: ",");

// Get the default worksheet from the workbook
WorkSheet ws = workbook.DefaultWorkSheet;

// Save the workbook as an Excel file
workbook.SaveAs("CsvToExcelConversion.xlsx");
' Load a CSV file into a WorkBook object specifying file format and delimiters
Dim workbook As WorkBook = WorkBook.LoadCSV("test.csv", fileFormat:= ExcelFileFormat.XLSX, ListDelimiter:= ",")

' Get the default worksheet from the workbook
Dim ws As WorkSheet = workbook.DefaultWorkSheet

' Save the workbook as an Excel file
workbook.SaveAs("CsvToExcelConversion.xlsx")
$vbLabelText   $csharpLabel

Read and Manipulate Converted CSV Files using IronXL

The IronXL WorkBook class represents an Excel sheet and uses this class to open an Excel file in C#. The code examples below will load the desired Excel file into a WorkBook object:

// Load WorkBook from a .xlsx file
var workbook = WorkBook.Load(@"Spreadsheets\\sample.xlsx");
// Load WorkBook from a .xlsx file
var workbook = WorkBook.Load(@"Spreadsheets\\sample.xlsx");
' Load WorkBook from a .xlsx file
Dim workbook = WorkBook.Load("Spreadsheets\\sample.xlsx")
$vbLabelText   $csharpLabel

WorkSheet objects can be found in numerous WorkBooks. These are the Excel document's worksheets. If the workbook has worksheets, you can get them by name by doing the following:

// Open a specific worksheet for reading by its name
var worksheet = workbook.GetWorkSheet("sheetnamegoeshere");
// Open a specific worksheet for reading by its name
var worksheet = workbook.GetWorkSheet("sheetnamegoeshere");
' Open a specific worksheet for reading by its name
Dim worksheet = workbook.GetWorkSheet("sheetnamegoeshere")
$vbLabelText   $csharpLabel

Code for reading the cell values:

// Read and output values from a range of cells elegantly
foreach (var cell in worksheet["A2:A10"])
{
    Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text);
}
// Read and output values from a range of cells elegantly
foreach (var cell in worksheet["A2:A10"])
{
    Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text);
}
' Read and output values from a range of cells elegantly
For Each cell In worksheet("A2:A10")
	Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text)
Next cell
$vbLabelText   $csharpLabel

The following code sample can update formulas or apply them to specific cells after loading and reading the workbook and worksheet. The following is the code:

// Set formulas for specific cells
worksheet["A1"].Formula = "Sum(B8:C12)";
worksheet["B8"].Formula = "=C9/C11";
worksheet["G30"].Formula = "Max(C3:C7)";

// Force recalculate all formula values in all sheets
workbook.EvaluateAll();
// Set formulas for specific cells
worksheet["A1"].Formula = "Sum(B8:C12)";
worksheet["B8"].Formula = "=C9/C11";
worksheet["G30"].Formula = "Max(C3:C7)";

// Force recalculate all formula values in all sheets
workbook.EvaluateAll();
' Set formulas for specific cells
worksheet("A1").Formula = "Sum(B8:C12)"
worksheet("B8").Formula = "=C9/C11"
worksheet("G30").Formula = "Max(C3:C7)"

' Force recalculate all formula values in all sheets
workbook.EvaluateAll()
$vbLabelText   $csharpLabel

Conclusion and IronXL Special Offer

IronXL transforms CSVs to Excel with just two lines of code, in addition to CSV processing in C#.

Without the need for Interop, using IronXL's Excel API is a breeze. Furthermore, IronXL also offers a wide range of features to interact with Excel WorkBook, WorkSheet and Cells level such as converting between popular formats, cell data formatting, merging cells, inserting math functions, and even managing charts and adding images.

You can launch without a watermark using IronXL trial licensing keys.

Licenses start at $799 and include one year of free support and updates.

IronPDF, IronXL, IronOCR, IronBarcode, and the IronWebscraper are all part of the Iron Software suite. Iron Software allows you to purchase their entire package for a reduced price. You can use all those tools at the price of two.

This is definitely an option worth exploring.

常见问题解答

我如何在 C# 中读取 CSV 文件?

您可以使用 IronXL 库中的 LoadCSV 方法在 C# 中读取 CSV 文件,这使您可以将 CSV 数据加载到 WorkBook 对象中以便进一步操作。

在 C# 中将 CSV 数据转换为 Excel 格式的最佳方法是什么?

在 C# 中将 CSV 数据转换为 Excel 格式的最佳方法是使用 IronXL。将您的 CSV 加载到 WorkBook 对象中,并使用 SaveAs 方法将其保存为 Excel 文件。

如何使用库在 C# 中处理具有自定义分隔符的 CSV 文件?

使用 IronXL,您可以通过在 LoadCSV 方法中指定分隔符作为可选参数来处理具有自定义分隔符的 CSV 文件。

我可以直接将 CSV 数据转换为 C# 中的数据库格式吗?

是的,您可以使用 IronXL 中的 ToDataTable 方法在 C# 中将 CSV 数据转换为数据库格式,该方法将数据转换为适合数据库操作的 DataTable 对象。

在 C# 中有哪些方法可以检查不存在的 CSV 文件?

在 C# 中,您可以使用 IronXL 的 Exists 方法在尝试加载之前检查 CSV 文件是否存在,从而避免与不存在的文件相关的错误。

在使用 C# 从 CSV 转换为 Excel 后,如何操作 Excel 数据?

在 C# 中将 CSV 转换为 Excel 后,您可以使用 IronXL 的功能来操作数据,例如格式化、合并单元格、插入数学函数以及添加图表或图像。

IronXL 读取和转换 C# 中 CSV 文件有哪些优势?

IronXL 提供的优势包括易于安装、无需额外的互操作、支持自定义分隔符,以及在 Excel 中转换和操作 CSV 数据的强大方法。

如何在 C# 中处理 CSV 数据中的特殊字符?

IronXL 可以通过允许您在加载 CSV 文件时指定文件编码和分隔符来处理 CSV 数据中的特殊字符,以确保数据的完整性和准确性。

IronXL 用户可获得哪些支持?

IronXL 许可证包括一年免费支持和更新,提供帮助并确保您获得最新的功能和修复。

Curtis Chau
技术作家

Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。

除了开发之外,Curtis 对物联网 (IoT) 有浓厚的兴趣,探索将硬件和软件集成的新方法。在空闲时间,他喜欢玩游戏和构建 Discord 机器人,将他对技术的热爱与创造力相结合。