
如何在 C# 中將 CSV 文件轉換為清單
在這個初學者教程中,我們將看到如何使用讀取CSV文件到C#中的列表,使用IronXL程式庫。 這是您在任何編程語言中需要了解的最基本的事情之一,因為CSV文件是一種非常常見的資料儲存和從一個系統或應用程式轉移到另一個的方式。 我們將涵蓋從設定專案到有效解析CSV文件的所有內容。
How to Convert CSV File into List in C#
- 在Visual Studio中建立一個C#控制台專案。
- 使用NuGet套件管理器安裝C# CSV程式庫。
- 使用
WorkBook.LoadCSV方法載入CSV文件。 - 從文件中讀取資料值並填充列表。
- 在控制台上列印列表。
設定您的專案
步驟1:建立一個新的C#專案
- **開啟Visual Studio:**在您的電腦上啟動Visual Studio。
- **建立一個新專案:**點擊"建立一個新專案"。 這將打開一個窗口,您可以選擇專案型別。
- **選擇專案型別:**選擇"控制台應用程式 (.NET Core)"作為您的專案型別,以求簡單。
- 為專案命名:將專案命名為CSVFileReader。
- **選擇位置:**在您的裝置上選擇一個合適的位置以保存此專案。
- **生成專案:**點擊"建立"以初始化您的新C#專案。
步驟2:安裝IronXL程式庫
- **打開NuGet套件管理器:**在Visual Studio中,轉到"工具"選單,然後選擇"NuGet套件管理器"並選擇"管理解決方案的NuGet套件..."。
- **搜尋IronXL:**點擊"瀏覽"選項卡,搜尋"IronXL.Excel"。

- **安裝IronXL:**在搜尋結果中找到IronXL套件,選擇並點擊"安裝"。確保您同意任何授權協議並檢查變更。
- **檢查安裝:**安裝完成後,您應該在專案的引用中看到IronXL。
現在,您的CSVFileReader專案已經設置了IronXL程式庫,您已準備好開始在C#中讀取和處理CSV文件。 此設置構成了我們將在本教程接下來的部分進行的CSV讀取任務的基礎。
Parsing and Processing CSV Files in C#
專案設置完成並安裝了IronXL程式庫,讓我們專注於解析和處理CSV文件。 我們將在自動生成於您的CSVFileReader專案中的Program.cs文件中進行工作。
步驟1:指定文件路徑
在我們能讀取任何資料之前,我們需要知道我們的CSV文件位於何處。 在Main方法中定義一個變數以儲存文件路徑。
string filename = "csvfile.csv"; // Replace with your actual file pathDim filename As String = "csvfile.csv" ' Replace with your actual file path步驟2:載入CSV文件
IronXL使得載入CSV文件變得簡單。使用WorkBook物件中。
var csv = WorkBook.LoadCSV(filename);Dim csv = WorkBook.LoadCSV(filename)步驟3:定義資料結構
建立一個類來表示CSV文件中的資料結構。例如,如果您的CSV包含有關人員的資訊,定義一個Person類,如下所示:
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}Public Class Person
Public Property Name() As String
Public Property Age() As Integer
End Class步驟4:解析CSV資料
在此步驟中,我們將解析CSV文件並填充List<Person>到資料中。 我們使用IronXL來處理CSV讀取,關鍵是正確處理CSV的每一行或每一列,考慮到標題和任何可能的空行。 以下是程式碼的詳細分解:
List<Person> people = new List<Person>();
bool isFirstRow = true; // Add a flag to check for the first row
foreach (var row in csv.WorkSheets[0].Rows)
{
if (isFirstRow)
{
isFirstRow = false; // Set the flag to false after skipping the first row
continue;
}
if (row.IsEmpty) continue; // Skip empty rows
var cells = row.ToArray();
var person = new Person()
{
Name = cells[0].StringValue,
Age = int.Parse(cells[1].StringValue) // Ensure this is a numeric value
};
people.Add(person);
}Dim people As New List(Of Person)()
Dim isFirstRow As Boolean = True ' Add a flag to check for the first row
For Each row In csv.WorkSheets(0).Rows
If isFirstRow Then
isFirstRow = False ' Set the flag to false after skipping the first row
Continue For
End If
If row.IsEmpty Then
Continue For ' Skip empty rows
End If
Dim cells = row.ToArray()
Dim person As New Person() With {
.Name = cells(0).StringValue,
.Age = Integer.Parse(cells(1).StringValue)
}
people.Add(person)
Next row在此解析過程中,我們首先初始化一個isFirstRow跳過CSV文件的標題行。 foreach迴圈遍歷CSV文件的每一行。在第一次迭代中,標題行被識別並跳過,確保僅處理資料行。 然後我們檢查每一行以確保它不是使用row.IsEmpty的空行。 此步驟至關緊要,以避免解析空行時出現錯誤。
對於每個資料行,我們將行轉換為單元格陣列 (Person物件。 正確分析和轉換資料型別,例如將"年齡"字串轉換為整數,是至關重要的。 解析後的people列表中。這種方法確保僅處理和儲存有效資料行,有效地處理例如非數值字串在數值列中的問題或意外的空行。
步驟5:顯示資料
在將CSV資料解析到List<Person>中後,下一個重要步驟是顯示和驗證資料。 這不僅有助於確保我們的解析成功,還可以使我們觀察輸出並進行快速資料質量檢查。 這是您如何實現這一點:
foreach (var person in people)
{
Console.WriteLine($"Name: {person.Name}, Age: {person.Age}");
}For Each person In people
Console.WriteLine($"Name: {person.Name}, Age: {person.Age}")
Next person這是完整的Program.cs程式碼:
using IronXL;
using System;
using System.Collections.Generic;
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
class Program
{
static void Main(string[] args)
{
string filename = @"C:\Users\tayya\Downloads\sample_data.csv"; // Replace with your actual file path
var csv = WorkBook.LoadCSV(filename);
List<Person> people = new List<Person>();
bool isFirstRow = true; // Add a flag to check for the first row
foreach (var row in csv.WorkSheets[0].Rows)
{
if (isFirstRow)
{
isFirstRow = false; // Set the flag to false after skipping the first row
continue;
}
if (row.IsEmpty) continue; // Skip empty rows
var cells = row.ToArray();
var person = new Person()
{
Name = cells[0].StringValue,
Age = int.Parse(cells[1].StringValue) // Ensure this is a numeric value
};
people.Add(person);
}
foreach (var person in people)
{
Console.WriteLine($"Name: {person.Name}, Age: {person.Age}");
}
}Imports IronXL
Imports System
Imports System.Collections.Generic
Public Class Person
Public Property Name() As String
Public Property Age() As Integer
End Class
Friend Class Program
Shared Sub Main(ByVal args() As String)
Dim filename As String = "C:\Users\tayya\Downloads\sample_data.csv" ' Replace with your actual file path
Dim csv = WorkBook.LoadCSV(filename)
Dim people As New List(Of Person)()
Dim isFirstRow As Boolean = True ' Add a flag to check for the first row
For Each row In csv.WorkSheets(0).Rows
If isFirstRow Then
isFirstRow = False ' Set the flag to false after skipping the first row
Continue For
End If
If row.IsEmpty Then
Continue For ' Skip empty rows
End If
Dim cells = row.ToArray()
Dim person As New Person() With {
.Name = cells(0).StringValue,
.Age = Integer.Parse(cells(1).StringValue)
}
people.Add(person)
Next row
For Each person In people
Console.WriteLine($"Name: {person.Name}, Age: {person.Age}")
Next person
End Sub程式碼的輸出
當您執行該文件時,會在控制台中顯示列表的資料:

處理不同的資料型別
在處理CSV文件中的各種資料型別時,重要的是根據每個資料列的具體型別來調整解析邏輯。 在Convert.ToInt32將字串轉換為整數。 這對避免型別不匹配錯誤至關重要。
對於更複雜的資料型別,例如日期,使用DateTime物件。 重要的是要了解您的CSV文件中使用的日期格式並確保它與您的程式碼中的預期格式匹配。 不一致的日期格式可能會導致解析錯誤或不正確的資料解釋。
結論
您剛學會如何使用IronXL在C#中讀取、解析和顯示CSV文件資料。 此方法可應用於不同型別的資料結構和文件格式。 因此,這對於尋求C#作為他們的主要語言的開發者來說,代表了一項非常有用的技能。
IronXL為使用者提供了一個免費試用以體驗其功能。 一旦試用期結束,IronXL的授權從$999的起始價開始。
請記住,必須處理異常和邊界情況,以便撰寫更強固的程式碼,特別是處理不同資料型別和使用大型文件時。 繼續嘗試和探索更多IronXL的功能,以增強您在C#中處理資料的能力。 編程愉快!

Curtis Chau擁有Carleton大學的電腦科學學士學位,專精於前端開發,擁有Node.js、TypeScript、JavaScript和React的專業知識。Curtis熱衷於建立直觀且美觀的使用者介面,喜愛使用現代框架並建立結構良好、視覺吸引力的手冊。
相關文章



