如何在 C# 中將 CSV 文件轉換為清單
在本篇初學者的教程中,我們將學習如何使用IronXL庫在 C# 中將CSV 檔案讀入清單。 嗯,這是任何程式語言中最基本的知識之一,因為 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 檔案。 我們將使用 Program.cs 文件,該文件會在您的CSVFileReader專案中自動產生。
步驟 1:指定檔案路徑
在讀取任何資料之前,我們需要知道 CSV 檔案位於哪裡。 在 Main 方法中定義一個變數來儲存檔案路徑。
string filename = "csvfile.csv"; // Replace with your actual file path
string filename = "csvfile.csv"; // Replace with your actual file path
Dim filename As String = "csvfile.csv" ' Replace with your actual file path
步驟 2:載入 CSV 文件
IronXL 可以輕鬆載入 CSV 檔案。使用 WorkBook.LoadCSV 方法將 CSV 檔案讀取到 WorkBook 物件中。
var csv = WorkBook.LoadCSV(filename);
var csv = WorkBook.LoadCSV(filename);
Dim csv = WorkBook.LoadCSV(filename)
步驟 3:定義資料結構
建立一個類別來表示 CSV 檔案中的資料結構。例如,如果您的 CSV 檔案包含人員資訊,請定義一個如下所示的類別:
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
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);
}
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
在此解析過程中,我們首先初始化一個 List<Person> 來儲存解析後的數據,並使用一個布林標誌 isFirstRow 來跳過 CSV 檔案的標題行。 foreach 循環遍歷 CSV 檔案的每一行。在第一次迭代中,會識別並跳過標題行,以確保只處理資料行。 然後我們使用 row.IsEmpty 檢查每一行,以確保它不會為空。 這一步驟對於避免解析過程中出現空白行錯誤至關重要。
對於每一行數據,我們將該行轉換為單元格數組(row.ToArray()),然後使用此數據建立一個 Person 物件。 正確分析和轉換資料類型至關重要,例如將"年齡"字串轉換為整數。 解析後的 Person 物件隨後被加入到我們的 people 清單中。這種方法確保只處理和儲存有效的資料行,從而有效地處理諸如數值列中出現非數字字串或意外的空白行等潛在問題。
步驟五:展示資料
將 CSV 資料解析成我們的 List<Person> 之後,下一個重要的步驟是顯示和驗證資料。 這不僅有助於確保解析成功,還可以讓我們觀察輸出結果並進行快速的資料品質檢查。 以下是實作方法:
foreach (var person in people)
{
Console.WriteLine($"Name: {person.Name}, Age: {person.Age}");
}
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}");
}
}
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 檔案中的各種資料類型時,必須根據每個資料列的具體類型來調整解析邏輯。 在 Person 類別範例中,雖然 Name 是一個字串,可以直接使用 StringValue 進行賦值,但像 Age@CODE-99437--@@ 進行賦值,但像 Age@CO將字串轉換為整數。 這對於避免類型不匹配錯誤至關重要。
對於更複雜的資料類型,例如日期,請使用 DateTime.Parse 將日期的字串表示形式轉換為 DateTime 物件。 請務必注意 CSV 檔案中使用的日期格式,並確保其與程式碼中預期的格式相符。 日期格式不一致會導致解析錯誤或資料解讀錯誤。
結論
您剛剛學習如何使用 IronXL 在 C# 中讀取、解析和顯示 CSV 檔案的資料。 這種方法可以應用於不同類型的資料結構和文件格式。 因此,對於所有選擇 C# 作為主要程式語言的開發人員來說,這都是一項非常有用的技能。
IronXL 提供免費試用,供使用者體驗其各項功能。 試用期結束後,IronXL 的許可開始以 $799 的起價進行。
請記住,為了編寫更健壯的程式碼,必須處理異常情況和邊界情況,尤其是在管理不同資料類型和使用大型檔案時。 繼續嘗試並探索 IronXL 的更多功能,以增強您在 C# 中處理資料的能力。 祝您編碼愉快!
常見問題解答
如何在 C# 中將 CSV 文件讀入列表?
您可以使用 IronXL 庫在 C# 中將 CSV 文件讀入列表。首先,在 Visual Studio 中創建一個 C# 控制台項目並通過 NuGet 包管理器安裝 IronXL。然後,使用 WorkBook.LoadCSV 方法加載 CSV 文件並將數據解析為列表。
我用什麼方法在 C# 中加載 CSV 文件?
要在 C# 中加載 CSV 文件,使用 IronXL 庫的 WorkBook.LoadCSV 方法,此方法以文件路徑作為參數。
如何定義數據結構以匹配 CSV 文件的內容?
定義一個類,例如“Person”類,其屬性名稱與您的 CSV 文件中的列名相匹配。這有助於將從 CSV 中檢索的數據結構化為面向對象的格式。
可以使用什麼技術來跳過 CSV 文件中的標題行?
為跳過標題行,實施一個布爾標誌來檢查該行是否為第一行,並通過繼續到下一次迭代來跳過處理。
在 C# 中解析 CSV 文件時,如何處理空行?
使用 IronXL 庫的行屬性,如 IsEmpty,檢查空行並在解析過程中跳過它們。
為什麼在處理 CSV 文件時正確處理不同數據類型很重要?
正確處理不同數據類型可確保數據準確處理,避免類型不匹配錯誤,尤其是在處理數字或日期欄位時。
處理 CSV 文件有哪些常見挑戰?
常見挑戰包括處理各種數據類型、跳過空行或格式不正確的行,以及確保數據解析和處理的準確性。
在 C# 中使用庫處理 CSV 文件有哪些優勢?
在 C# 中使用 IronXL 庫進行 CSV 處理,可以利用其直觀的方法簡化 CSV 文件的加載和解析,讓開發人員高效處理數據。
設置 C# 項目以便讀取 CSV 文件應遵循哪些步驟?
首先在 Visual Studio 中創建一個 C# 控制台項目,使用 NuGet 包管理器安裝 IronXL 庫,並使用 WorkBook.LoadCSV 方法將 CSV 文件加載並解析到列表中。

