跳過到頁腳內容
使用 IRONXL

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

在這個初學者教程中,我們將看到如何使用IronXL程式庫將CSV文件讀取C#中的清單。 這是您在任何程式語言中需要了解的最基礎的事情之一,因為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. 選擇專案類型:選擇"Console App (.NET Core)"作為您的專案類型以簡化操作。
  4. 命名您的專案:將您的專案命名為CSVFileReader
  5. 選擇位置:選擇適合的位置在您的設備上保存此專案。
  6. 生成專案:點擊"建立"初始化您的新C#專案。

步驟2:安裝IronXL程式庫

  1. 開啟NuGet套件管理器:在Visual Studio中,前往"工具"選單,然後選擇"NuGet套件管理器"並選擇"管理解決方案的NuGet套件..."。
  2. 瀏覽IronXL:點擊"瀏覽"標籤並搜索"IronXl.Excel"。

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

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

步驟2:載入CSV文件

IronXL使載入CSV文件變得簡單。使用WorkBook物件中。

var csv = WorkBook.LoadCSV(filename);
var 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; }
}
$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);
}
$vbLabelText   $csharpLabel

在此解析過程中,我們首先初始化一個isFirstRow來跳過CSV文件的標題行。 foreach循環遍歷CSV文件的每一行。在第一次迭代期間,標題行被識別並跳過,確保只有數據行得到處理。 然後,我們檢查每行是否不為空,使用row.IsEmpty。 這一步對於避免解析錯誤非常重要,尤其是在有空行的情況下。

對於每行數據,我們將行轉換為一個單元格陣列(Person物件。 正確分析並轉換數據類型至關重要,例如將'Age'字串轉換為整數。 解析的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}");
}
$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}");
    }
}
$vbLabelText   $csharpLabel

代碼的輸出

當您執行文件時,它會在主控台中顯示列表數據:

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

處理不同的數據類型

當處理CSV文件中的各種類型數據時,必須根據每個數據列的特定類型調整解析邏輯。 在Convert.ToInt32將其從字串轉換為整數。 這對於避免類型不匹配錯誤非常重要。

對於更複雜的數據類型,例如日期,使用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 在佛罗里达州迈阿密长大,曾在佛罗里达大学学习计算机科学和统计学。

Iron Support Team

We're online 24 hours, 5 days a week.
Chat
Email
Call Me