在實際環境中測試
在生產環境中測試無浮水印。
在任何需要的地方都能運作。
在這個初學者的教程中,我們將會看到如何 讀取CSV檔案 進入一個 C# 清單 使用該 IronXL 庫。這是任何程式語言中最基本的知識之一,因為 CSV 文件是一種非常常見的數據存儲和系統或應用之間遷移數據的方法。我們將涵蓋從設置專案到有效分析 CSV 文件的所有內容。
在Visual Studio中創建一個C#控制台項目。
使用NuGet包管理器安裝C# CSV庫。
使用 WorkBook.LoadCSV
方法加載CSV文件。
從文件中讀取數據值並填充列表。
開啟 Visual Studio:在您的電腦上啟動 Visual Studio。
建立一個新專案:點擊 "建立一個新專案"。這會打開一個視窗,您可以在那裡選擇專案類型。
選擇專案類型:選擇 "Console App" (.NET Core)選擇專案類型以簡化操作。
命名您的專案:將您的專案命名為 CSVFileReader。
選擇位置:在您的設備上選擇適合的保存位置來保存這個專案。
開啟 NuGet 套件管理員:在 Visual Studio 中,前往「工具」菜單,然後選擇「NuGet 套件管理員」並選擇「管理解決方案的 NuGet 套件...」。
瀏覽 IronXL:點擊「瀏覽」標籤並搜索「IronXL.Excel」。
安裝 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
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
之後
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 檔案中使用的日期格式,並且確保它與代碼中的預期格式一致。日期格式不一致可能會導致解析錯誤或數據解釋錯誤。
您剛剛學會了如何使用IronXL在C#中讀取、解析和顯示CSV文件的數據。這種方法可以應用於不同類型的數據結構和文件格式。因此,這對於每一位選擇C#作為主要語言的開發者來說是一項非常有用的技能。
IronXL提供了一個 免費試用 供用戶體驗其功能。試用期結束後,IronXL的授權起價為$749。
請記住,處理異常和邊緣情況是編寫更健壯代碼的重要一環,尤其是在管理不同數據類型和使用大型文件時。繼續實驗和探索IronXL的更多功能,以增強您在C#中的數據處理能力。祝您編程愉快!