在生產環境中測試,無水印。
在任何需要的地方都能運行。
獲得 30 天的全功能產品。
在幾分鐘內上手運行。
試用產品期間完全訪問我們的支援工程團隊
在本初學者教程中,我們將學習如何使用IronXL庫將CSV文件讀取到C#中的列表中。 嗯,這是在任何程式語言中你需要了解的最基本的事情之一,因為 CSV 檔案是一種非常常見的資料存儲和從一個系統或應用程式轉移到另一個系統或應用程式的方式。 我們將從設置您的項目到有效解析 CSV 文件涵蓋所有內容。
在 Visual Studio 中創建一個 C# 控制台專案。
使用 NuGet 套件管理器安裝 C# CSV 函式庫。
使用WorkBook.LoadCSV
方法載入CSV檔案。
從檔案中讀取數據值並填入列表。
開啟 Visual Studio:在您的電腦上啟動 Visual Studio。
建立新專案:點擊「建立新專案」。 這會開啟一個視窗,您可以在此選擇專案類型。
選擇專案類型:為了簡單起見,請選擇「控制台應用程式(.NET Core)」作為您的專案類型。
命名您的專案:將您的專案命名為CSVFileReader。
選擇位置:在您的設備上選擇合適的位置以保存此專案。
打開 NuGet 套件管理員:在 Visual Studio 中,進入“工具”菜單,然後選擇“NuGet 套件管理員”,並選擇“為解決方案管理 NuGet 套件...”。
瀏覽 IronXL:點擊“瀏覽”選項卡,然後搜尋“IronXL.Excel”。
安裝 IronXL:在搜索結果中找到 IronXL 套件,選擇它並點擊“安裝”。確保您同意任何許可協議並檢查變更內容。
檢查安裝:安裝後,您應該在專案的引用中看到 IronXL。
現在,您的CSVFileReader專案已設置了IronXL庫,您可以開始在C#中讀取和處理CSV文件。 這個設置構成了我們在本教程後續部分即將進行的 CSV 讀取任務的基礎。
在專案設置完成且安裝了IronXL庫後,我們來專注於解析和處理CSV文件。 我們將在自動生成於CSVFileReader專案中的Program.cs
文件中工作。
在我們可以讀取任何數據之前,我們需要知道我們的 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
IronXL 使載入 CSV 檔案變得簡單。使用 WorkBook.LoadCSV
方法將 CSV 檔案讀取到 WorkBook
物件中。
var csv = WorkBook.LoadCSV(filename);
var csv = WorkBook.LoadCSV(filename);
Dim csv = WorkBook.LoadCSV(filename)
為您的 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
在這一步驟中,我們將解析 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
在這個解析過程中,我們首先初始化一個List<Person>
來存儲解析後的數據,並使用一個布林旗標isFirstRow
來跳過CSV文件的標題行。 foreach
迴圈遍歷 CSV 文件的每一行。在第一次迭代期間,標題行會被識別並跳過,以確保只處理數據行。 接著,我們檢查每一行以確保其不為空,使用 row.IsEmpty
。 這個步驟對於避免空行解析錯誤至關重要。
對於每個資料列,我們將該列轉換為一個單元格陣列(row.ToArray()
),然後使用這些資料創建一個Person
對象。 正確分析和轉換數據類型至關重要,例如將“Age”字符串轉換為整數。 解析後的Person
物件隨後被加入到我們的people
清單中。此方法可確保僅處理和存儲有效的資料列,有效處理像數字欄位中的非數字字串或意外的空白列等潛在問題。
將 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
以下是完整的 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
當您運行該文件時,它將在控制台中顯示列表的數據:
在處理 CSV 文件中的各種數據類型時,為每個數據列的特定類型調整解析邏輯是很重要的。 在Person
類別的範例中,Name
是字串,可以直接使用StringValue
指派,而像Age
這樣的數字欄位則需要使用Int32.Parse
或Convert.ToInt32
從字串轉換為整數。 這對於避免型別不匹配錯誤至關重要。
對於更複雜的數據類型,如日期,使用DateTime.Parse
將日期的字串表示轉換為DateTime
物件。 重要的是要注意 CSV 文件中使用的日期格式,並確保它與您程式碼中預期的格式相符。 不一致的日期格式可能導致解析錯誤或數據解釋不正確。
您剛剛學習了如何使用 C# 中的 IronXL 來讀取、解析和顯示 CSV 文件的數據。 這種方法可以用於不同類型的資料結構和檔案格式。 因此,這對於所有將C#作為其主要語言選擇的開發者來說,都是一項非常有用的技能。
IronXL 提供免費試用,讓用戶體驗其功能。 試用期結束後,IronXL 的授權價格起始於 $749。
請記住,例外和邊緣情況必須妥善處理,以編寫更健壯的代碼,特別是在處理不同數據類型和使用大型文件時。 繼續嘗試和探索IronXL的更多功能,以增強您在C#中處理數據的能力。 快樂編程!