跳過到頁腳內容
使用 IRONXL

如何在 C# 中將 CSV 文件轉換為清單

In this tutorial for beginners, we are going to see how to read CSV files into a list in C# using the IronXL library. 這是你在任何編程語言中需要知道的最基本的事情之一,因為CSV檔案是一種非常常見的數據存儲和從一個系統或應用程序轉移到另一個系統或應用程序的方式。 我們將涵蓋從設置項目到有效解析CSV文件的所有內容。

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

  1. 在Visual Studio中創建一個C#控制檯項目。
  2. 使用NuGet程序包管理器安裝C# CSV庫。
  3. 使用WorkBook.LoadCSV方法加載CSV文件。
  4. 從文件中讀取數據值並填充列表。
  5. 在控制檯上打印列表。

設置您的項目

步驟1:創建一個新的C#項目

  1. 打開Visual Studio:在您的計算機上啟動Visual Studio。
  2. 創建一個新項目:點擊“創建一個新項目”。 這將打開一個窗口,您可以選擇項目類型。
  3. 選擇項目類型:選擇“控制檯應用程序(.NET Core)”作為您的項目類型,以簡化項目。
  4. 命名您的項目:將您的項目命名為CSVFileReader
  5. 選擇位置:選擇您設備上合適的位置來保存這個項目。
  6. 生成項目:點擊“創建”來初始化您的新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讀取任務奠定了基礎。

解析和處理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
$vbLabelText   $csharpLabel

步驟2:加載CSV文件

IronXL使加載CSV文件變得簡單明瞭。使用WorkBook.LoadCSV方法將CSV文件讀取到WorkBook對象中。

var csv = WorkBook.LoadCSV(filename);
var csv = WorkBook.LoadCSV(filename);
Dim csv = WorkBook.LoadCSV(filename)
$vbLabelText   $csharpLabel

步驟3:定義數據結構

創建一個類來表示您的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
$vbLabelText   $csharpLabel

步驟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
$vbLabelText   $csharpLabel

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

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

步驟5:顯示數據

在將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
$vbLabelText   $csharpLabel

這是完整的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
$vbLabelText   $csharpLabel

代碼的輸出

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

如何在C#中將CSV文件轉換為列表:圖2 - 列表輸出

處理不同的數據類型

在處理CSV文件中的各種數據類型時,根據每個數據列的具體類型調整解析邏輯是很重要的。 在Person類示例中,雖然Name是一個字符串,可以直接使用StringValue分配,但像Age這樣的數字字段需要使用Int32.ParseConvert.ToInt32將字符串轉換為整數。 這對於避免類型不匹配錯誤至關重要。

對於更復雜的數據類型,如日期,使用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 文件加載並解析到列表中。

Jordi Bardia
軟體工程師
Jordi 在 Python、C# 和 C++ 上最得心應手,當他不在 Iron Software 展現技術時,便在做遊戲編程。在分担产品测测试,产品开发和研究的责任时,Jordi 为持续的产品改进增值。他说这种多样化的经验使他受到挑战并保持参与, 而这也是他与 Iron Software 中工作一大乐趣。Jordi 在佛罗里达州迈阿密长大,曾在佛罗里达大学学习计算机科学和统计学。