如何在 C# 中將 CSV 檔案轉換為列表
在本篇初學者的教程中,我們將學習如何使用IronXL庫在 C# 中將CSV 檔案讀入清單。 嗯,這是任何程式語言中最基本的知識之一,因為 CSV 檔案是儲存資料並將其從一個系統或應用程式傳輸到另一個系統的非常常見的方式。 我們將涵蓋從專案設定到有效解析 CSV 檔案的所有內容。
如何在 C# 中將 CSV 檔案轉換為列表
- 在 Visual Studio 中建立一個 C# 控制台專案。
- 使用 NuGet 套件管理器安裝 C# CSV 庫。
- 使用
WorkBook.LoadCSV方法載入 CSV 檔案。 - 從檔案中讀取資料值並填入清單。
- 將清單列印到控制台。
設定您的項目
步驟 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](/static-assets/excel/blog/csharp-read-csv-file-into-list-tutorial/csharp-read-csv-file-into-list-tutorial-1.webp)3.安裝 IronXL:在搜尋結果中找到 IronXL 軟體包,選擇它,然後按一下"安裝"。確保您同意所有許可協議並查看更改內容。 4.檢查安裝:安裝完成後,您應該在項目的引用中看到 IronXL 的引用。
現在,您的CSVFileReader專案已設定好 IronXL 庫,您可以開始在 C# 中讀取和處理 CSV 檔案了。 此設定構成了我們將在本教程後續章節中進行的 CSV 讀取任務的基礎。
使用 C# 解析和處理 CSV 文件
專案設定完畢,IronXL 庫也已安裝,接下來我們將專注於解析和處理 CSV 檔案。 我們將使用Program.cs文件,該文件是在您的CSVFileReader專案中自動產生的。
步驟 1:指定檔案路徑
在讀取任何資料之前,我們需要知道 CSV 檔案位於哪裡。 在Main方法中定義一個變數來儲存檔案路徑。
string filename = "csvfile.csv"; // Replace with your actual file pathstring filename = "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);步驟 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; }
}步驟 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);
}在這個解析過程中,我們先初始化一個List<Person>儲存解析後的數據,並使用布林標誌isFirstRow跳過 CSV 檔案的標題行。 foreach循環遍歷 CSV 檔案的每一行。在第一次迭代中,會識別並跳過標題行,從而確保只處理資料行。 然後我們使用row.IsEmpty檢查每一行,以確保它不為空。 這一步驟對於避免解析過程中出現空白行錯誤至關重要。
對於每一行數據,我們將該行轉換為單元格數組( row.ToArray() ),然後使用此數據建立Person物件。 正確分析和轉換資料類型至關重要,例如將"年齡"字串轉換為整數。 解析後的Person物件隨後被加入到我們的people清單中。這種方法確保只處理和儲存有效的資料行,從而有效處理諸如數值列中出現非數字字串或意外的空白行等潛在問題。
步驟五:展示數據
將 CSV 資料解析到我們的List<Person>中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}");
}以下是完整的 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}");
}
}程式碼輸出
運行該文件後,它會在控制台中顯示列表資料:
處理不同的資料類型
在處理 CSV 檔案中的各種資料類型時,必須根據每個資料列的具體類型來調整解析邏輯。 在Person類別範例中,雖然Name是一個字串,可以直接使用StringValue賦值,但像Age這樣的數值欄位需要使用Int32.Parse或Convert.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 檔案的載入和解析,使開發人員能夠有效率地處理資料。
要設定一個用於讀取 CSV 檔案的 C# 項目,我應該遵循哪些步驟?
首先在 Visual Studio 中建立一個 C# 控制台項目,使用 NuGet 套件管理器安裝 IronXL 庫,然後使用WorkBook.LoadCSV方法將 CSV 檔案載入並解析到清單中。






