使用IRONXL

如何將 CSV 檔案轉換為 C# 中的清單

發佈 2024年1月27日
分享:

在這個初學者的教程中,我們將會看到如何 讀取CSV檔案 進入一個 C# 清單 使用該 IronXL 庫。這是任何程式語言中最基本的知識之一,因為 CSV 文件是一種非常常見的數據存儲和系統或應用之間遷移數據的方法。我們將涵蓋從設置專案到有效分析 CSV 文件的所有內容。

如何在C#中將CSV文件轉換為列表

  1. 在Visual Studio中創建一個C#控制台項目。

  2. 使用NuGet包管理器安裝C# CSV庫。

  3. 使用 WorkBook.LoadCSV 方法加載CSV文件。

  4. 從文件中讀取數據值並填充列表。

  5. 在控制台上打印列表。

設置您的專案

第一步:建立一個新的 C# 專案

  1. 開啟 Visual Studio:在您的電腦上啟動 Visual Studio。

  2. 建立一個新專案:點擊 "建立一個新專案"。這會打開一個視窗,您可以在那裡選擇專案類型。

  3. 選擇專案類型:選擇 "Console App" (.NET Core)選擇專案類型以簡化操作。

  4. 命名您的專案:將您的專案命名為 CSVFileReader

  5. 選擇位置:在您的設備上選擇適合的保存位置來保存這個專案。

  6. 生成專案:點擊 "Create" 以初始化您的新 C# 專案。

步驟 2:安裝 IronXL 函式庫

  1. 開啟 NuGet 套件管理員:在 Visual Studio 中,前往「工具」菜單,然後選擇「NuGet 套件管理員」並選擇「管理解決方案的 NuGet 套件...」。

  2. 瀏覽 IronXL:點擊「瀏覽」標籤並搜索「IronXL.Excel」。

    如何在C#中將CSV文件轉換為列表:圖1 - IronXL

  3. 安裝 IronXL:在搜索結果中找到 IronXL 套件,選擇它,然後點擊「安裝」。確保您同意任何許可協議並審查更改。

  4. 檢查安裝:安裝後,您應該能在專案的引用中看到 IronXL。

現在,您的 CSVFileReader 專案已經設定好使用 IronXL 庫,您可以開始用 C# 讀取和處理 CSV 文件。這個設置為我們在本教程後續部分將進行的 CSV 讀取任務奠定了基礎。

在 C&num 中解析和處理 CSV 文件

在設置好項目並安裝 IronXL 庫之後,讓我們專注於解析和處理 CSV 文件。我們將在 CSVFileReader 項目中自動生成的 Program.cs 文件中工作。

第 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
VB   C#

第 2 步:載入 CSV 檔案

IronXL 讓載入 CSV 檔案變得簡單。使用 WorkBook.LoadCSV 方法將 CSV 檔案讀取到 WorkBook 物件中。

var csv = WorkBook.LoadCSV(filename);
var csv = WorkBook.LoadCSV(filename);
Dim csv = WorkBook.LoadCSV(filename)
VB   C#

第三步:定義數據結構

創建一個類來表示CSV文件中的數據結構。例如,如果你的CSV包含有關人的信息,定義一個 Person 類如下:

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
VB   C#

第四步:解析 CSV 資料

在這一步中,我們將解析 CSV 文件並填充一個 `List我們正在使用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
VB   C#

在此解析過程中,我們首先初始化一個 List<Person>來存儲解析數據並使用布林旗標 isFirstRow 來跳過 CSV 文件的標頭行。 foreach 迴圈遍歷 CSV 文件的每一行。在第一次迭代中,標頭行被識別並跳過,確保只有數據行被處理。我們然後檢查每一行以確保它不是空的,使用 row.IsEmpty。這一步對於避免解析空行的錯誤是至關重要的。

對於每一個數據行,我們將行轉換為一個單元格陣列。 (row.ToArray()) 然後使用這些數據創建一個 Person 對象。正確分析和轉換數據類型非常重要,例如將 'Age' 字符串轉換為整數。解析後的 Person 對象被添加到我們的 people 列表中。這種方法確保只有有效的數據行被處理和存儲,有效地處理了潛在的問題,如數字列中的非數字字符串或意外的空行。

第5步:顯示資料

將CSV資料解析到我們的 List 之後,下一個重要的步驟是顯示和驗證數據。這不僅有助於確保我們的解析成功,還可以讓我們觀察輸出並進行快速的數據質量檢查。以下是您可以實現的方法:

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
VB   C#

以下是完整的 Program.cs 代碼:

using IronXL;

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;

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

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
End Class
VB   C#

代碼輸出的內容

當您運行該文件時,它會在控制台中顯示列表的數據:

如何將 CSV 檔案轉換為 C# 中的列表:圖 2 - 列表輸出

處理不同數據類型

在處理 CSV 檔案中的各種數據類型時,重要的是根據每個數據列的具體類型調整解析邏輯。在 Person 類的範例中,雖然 Name 是字符串,可以直接使用 StringValue 分配,但像 Age 這樣的數值字段需要使用 Int32.ParseConvert.ToInt32 從字符串轉換為整數。這是避免類型不匹配錯誤的必要操作。

對於更複雜的數據類型,例如日期,使用 DateTime.Parse 將日期的字符串表示轉換為 DateTime 物件。關注你的 CSV 檔案中使用的日期格式,並且確保它與代碼中的預期格式一致。日期格式不一致可能會導致解析錯誤或數據解釋錯誤。

結論

您剛剛學會了如何使用IronXL在C#中讀取、解析和顯示CSV文件的數據。這種方法可以應用於不同類型的數據結構和文件格式。因此,這對於每一位選擇C#作為主要語言的開發者來說是一項非常有用的技能。

IronXL提供了一個 免費試用 供用戶體驗其功能。試用期結束後,IronXL的授權起價為$749。

請記住,處理異常和邊緣情況是編寫更健壯代碼的重要一環,尤其是在管理不同數據類型和使用大型文件時。繼續實驗和探索IronXL的更多功能,以增強您在C#中的數據處理能力。祝您編程愉快!

< 上一頁
如何在C#中將CSV導入到Datatable
下一個 >
如何在 VB .NET 中保存 Excel 文件

準備開始了嗎? 版本: 2024.10 剛剛發布

免費 NuGet 下載 總下載次數: 1,023,839 查看許可證 >