跳至頁尾內容
USING IRONXL
如何將CSV檔案轉換為C#中的清單 | IronXL

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

在這個初學者教程中,我們將看到如何使用讀取CSV文件C#中的列表,使用IronXL程式庫。 這是您在任何編程語言中需要了解的最基本的事情之一,因為CSV文件是一種非常常見的資料儲存和從一個系統或應用程式轉移到另一個的方式。 我們將涵蓋從設定專案到有效解析CSV文件的所有內容。

How to Convert CSV File into List in C

  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"。

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

  1. 安裝IronXL:在搜尋結果中找到IronXL套件,選擇並點擊"安裝"。確保您同意任何授權協議並檢查變更。
  2. 檢查安裝:安裝完成後,您應該在專案的引用中看到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 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物件中。

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

在此解析過程中,我們首先初始化一個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}");
}
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

程式碼的輸出

當您執行該文件時,會在控制台中顯示列表的資料:

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

處理不同的資料型別

在處理CSV文件中的各種資料型別時,重要的是根據每個資料列的具體型別來調整解析邏輯。 在Convert.ToInt32將字串轉換為整數。 這對避免型別不匹配錯誤至關重要。

對於更複雜的資料型別,例如日期,使用DateTime物件。 重要的是要了解您的CSV文件中使用的日期格式並確保它與您的程式碼中的預期格式匹配。 不一致的日期格式可能會導致解析錯誤或不正確的資料解釋。

結論

您剛學會如何使用IronXL在C#中讀取、解析和顯示CSV文件資料。 此方法可應用於不同型別的資料結構和文件格式。 因此,這對於尋求C#作為他們的主要語言的開發者來說,代表了一項非常有用的技能。

IronXL為使用者提供了一個免費試用以體驗其功能。 一旦試用期結束,IronXL的授權從$999的起始價開始。

請記住,必須處理異常和邊界情況,以便撰寫更強固的程式碼,特別是處理不同資料型別和使用大型文件時。 繼續嘗試和探索更多IronXL的功能,以增強您在C#中處理資料的能力。 編程愉快!

常見問題

我如何將CSV檔案讀入C#中的清單?

您可以通過使用IronXL程式庫將CSV檔案讀入C#中的清單。首先,在Visual Studio中建立C#主控台專案,並通過NuGet套件管理器安裝IronXL。然後,使用WorkBook.LoadCSV方法載入CSV檔案並將其解析為清單。

我應該使用什麼方法來載入C#中的CSV檔案?

要在C#中載入CSV檔案,使用IronXL程式庫的WorkBook.LoadCSV方法,此方法以檔案路徑作為參數。

我如何定義一個符合CSV檔案內容的資料結構?

定義一個類,例如'Person'類,具有與CSV檔案中的列相匹配的屬性。這有助於將從CSV檔案中檢索到的資料結構化為面向物件的格式。

可以使用什麼技術來跳過CSV檔案中的標題行?

要跳過標題行,實現一個布林標誌以檢查該行是否為第一行,並通過繼續下一次迭代來跳過其處理。

我如何在解析CSV檔案時處理空行?

使用IronXL程式庫的行屬性,如IsEmpty,以檢查空行,並在解析過程中跳過它們。

處理CSV檔案時處理不同資料型別的重要性是什麼?

正確處理不同的資料型別可確保資料被準確處理,並防止型別不匹配錯誤,特別是在處理數字或日期字段時。

處理CSV檔案時常見的挑戰有哪些?

常見挑戰包括處理各種資料型別、跳過空行或格式錯誤行,以及確保資料的準確解析和處理。

在C#中使用程式庫進行CSV檔案處理有什麼好處?

使用IronXL程式庫進行C#的CSV處理,通過其直觀的方法簡化了CSV檔案的載入和解析,允許開發者有效地處理資料。

應遵循哪些步驟來設定一個C#專案以供CSV檔案讀取?

先在Visual Studio中建立C#主控台專案,使用NuGet套件管理器安裝IronXL程式庫,然後使用WorkBook.LoadCSV方法載入並解析CSV檔案到清單中。

Curtis Chau
技術作家

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

除了開發,Curtis對物聯網(IoT)有濃厚的興趣,探索創新的方法來整合硬體和軟體。在空閒時間,他喜歡玩遊戲和建立Discord機器人,結合他對技術的熱愛與創造力。

Iron 支援團隊

我們線上24小時,每週5天。
聊天
電子郵件
給我打電話