跳過到頁腳內容
使用 IRONXL
如何使用 IronXL 在 C# 中讀取 CSV 檔案

在 C#中讀取 CSV 文件:教程

使用各種 Excel 格式通常需要讀取數據,然後以程式設計方式重新配置資料。 在本文中,我們將學習如何使用 IronXL(非常適合這項工作的工具)在 C# 中讀取 CSV 檔案並解析 Excel 電子表格中的資料。

什麼是CSV?

CSV 是一種簡單的資料格式,但可能存在許多差異; 在我們的 C# 專案中,以程式設計方式讀取資料可能很困難,因為它使用多個分隔符號來區分資料的行和列。 本文將向您展示如何使用IronXL 庫讀取 CSV 檔案。


1. 如何在 C# 中讀取 CSV 文件

在 MVC、ASP.NET 或 .NET Core 中使用 IronXL 讀取 CSV 檔案之前,您需要先安裝它。 以下是簡要介紹。

  1. 在 Visual Studio 中,選擇"專案"選單
  2. 管理 NuGet 套件
  3. 搜尋 IronXL.Excel
  4. 安裝

C# 讀取 CSV 檔案教學課程,圖 1:在 Visual Studio 的 NuGet 套件管理器中搜尋 IronXL 在 Visual Studio 的 NuGet 套件管理器中搜尋 IronXL

當您需要在 C# 中讀取 CSV 檔案時,IronXL 是完美的工具。 您可以讀取以逗號或其他任何分隔符號分隔的 CSV 文件,如下面的程式碼片段所示。

// Load a CSV file and interpret it as an Excel-like workbook
WorkBook workbook = WorkBook.LoadCSV("Weather.csv", fileFormat: ExcelFileFormat.XLSX, ListDelimiter: ",");

// Access the default worksheet in the workbook
WorkSheet ws = workbook.DefaultWorkSheet;

// Save the workbook to a new Excel file
workbook.SaveAs("Csv_To_Excel.xlsx");
// Load a CSV file and interpret it as an Excel-like workbook
WorkBook workbook = WorkBook.LoadCSV("Weather.csv", fileFormat: ExcelFileFormat.XLSX, ListDelimiter: ",");

// Access the default worksheet in the workbook
WorkSheet ws = workbook.DefaultWorkSheet;

// Save the workbook to a new Excel file
workbook.SaveAs("Csv_To_Excel.xlsx");
' Load a CSV file and interpret it as an Excel-like workbook
Dim workbook As WorkBook = WorkBook.LoadCSV("Weather.csv", fileFormat:= ExcelFileFormat.XLSX, ListDelimiter:= ",")

' Access the default worksheet in the workbook
Dim ws As WorkSheet = workbook.DefaultWorkSheet

' Save the workbook to a new Excel file
workbook.SaveAs("Csv_To_Excel.xlsx")
$vbLabelText   $csharpLabel

Output:

C# 中讀取 CSV 檔案:教程,圖 2:以逗號分隔符號輸出 CSV 文件 輸出以逗號分隔的 CSV 文件

代碼解釋:

創建了一個WorkBook物件。 然後使用 WorkBook 物件的LoadCSV方法來指定 CSV 的名稱、格式以及要讀取的 CSV 檔案中使用的分隔符號。 在這種情況下,逗號用作分隔符號。

然後創建一個WorkSheet物件。 這裡將放置 CSV 檔案的內容。 文件將以新名稱和新格式儲存。

C# 讀取 CSV 檔案教程,圖 3:資料在 Microsoft Excel 中顯示 資料以 Microsoft Excel 形式顯示


2. IronXL for Excel 文件

在您的專案中使用 IronXL,它是一種在 C# 中處理 Excel 檔案格式的簡化方法。 你可以透過直接下載的方式安裝 IronXL 。 或者,您可以使用適用於 Visual Studio 的 NuGet Install 。 該軟體可免費用於開發。

dotnet add package IronXL.Excel

3. 載入WorkBook並存取WorkSheet

WorkBook是 IronXL 的一個類,其物件提供對 Excel 檔案及其所有功能的完全存取權。 例如,如果我們想存取一個 Excel 文件,我們可以使用以下程式碼:

// Load the Excel file
WorkBook wb = WorkBook.Load("sample.xlsx"); // Excel file path
// Load the Excel file
WorkBook wb = WorkBook.Load("sample.xlsx"); // Excel file path
' Load the Excel file
Dim wb As WorkBook = WorkBook.Load("sample.xlsx") ' Excel file path
$vbLabelText   $csharpLabel

要存取 Excel 檔案的特定工作表,IronXL 提供了WorkSheet類別。

// Access a specific worksheet by name
WorkSheet ws = wb.GetWorkSheet("Sheet1"); // by sheet name
// Access a specific worksheet by name
WorkSheet ws = wb.GetWorkSheet("Sheet1"); // by sheet name
' Access a specific worksheet by name
Dim ws As WorkSheet = wb.GetWorkSheet("Sheet1") ' by sheet name
$vbLabelText   $csharpLabel

取得 Excel 工作表ws後,您可以從中提取任何類型的資料並對其執行所有 Excel 功能。 可以透過以下步驟從 Excel 工作表ws存取資料:

using IronXL;

class Program
{
    static void Main(string[] args)
    {
        // Load the workbook and access a specific worksheet
        WorkBook wb = WorkBook.Load("sample.xlsx");
        WorkSheet ws = wb.GetWorkSheet("Sheet1");

        // Iterate through a range of cells and display their values
        foreach (var cell in ws["A2:A10"])
        {
            Console.WriteLine("Value is: {0}", cell.Text);
        }
        Console.ReadKey();
    }
}
using IronXL;

class Program
{
    static void Main(string[] args)
    {
        // Load the workbook and access a specific worksheet
        WorkBook wb = WorkBook.Load("sample.xlsx");
        WorkSheet ws = wb.GetWorkSheet("Sheet1");

        // Iterate through a range of cells and display their values
        foreach (var cell in ws["A2:A10"])
        {
            Console.WriteLine("Value is: {0}", cell.Text);
        }
        Console.ReadKey();
    }
}
Imports IronXL

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Load the workbook and access a specific worksheet
		Dim wb As WorkBook = WorkBook.Load("sample.xlsx")
		Dim ws As WorkSheet = wb.GetWorkSheet("Sheet1")

		' Iterate through a range of cells and display their values
		For Each cell In ws("A2:A10")
			Console.WriteLine("Value is: {0}", cell.Text)
		Next cell
		Console.ReadKey()
	End Sub
End Class
$vbLabelText   $csharpLabel

4. 將 Excel 工作表讀取為資料表

使用 IronXL,將 Excel WorkSheet作為資料表進行操作非常容易。

DataTable dt = ws.ToDataTable(true); // Converts the worksheet to a DataTable, using the first row as column names
DataTable dt = ws.ToDataTable(true); // Converts the worksheet to a DataTable, using the first row as column names
Dim dt As DataTable = ws.ToDataTable(True) ' Converts the worksheet to a DataTable, using the first row as column names
$vbLabelText   $csharpLabel

請使用以下命名空間:

using IronXL;
using System.Data;
using IronXL;
using System.Data;
Imports IronXL
Imports System.Data
$vbLabelText   $csharpLabel

編寫以下程式碼:

class Program
{
    static void Main(string[] args)
    {
        // Load the workbook and access a specific worksheet
        WorkBook wb = WorkBook.Load("Weather.xlsx"); // Your Excel file Name
        WorkSheet ws = wb.GetWorkSheet("Sheet1");

        // Parse worksheet into datatable
        DataTable dt = ws.ToDataTable(true); // Parse Sheet1 of sample.xlsx file into DataTable

        // Iterate through rows and columns to display their values
        foreach (DataRow row in dt.Rows) // Access rows
        {
            for (int i = 0; i < dt.Columns.Count; i++) // Access columns of corresponding row
            {
                Console.Write(row[i] + "  ");
            }
            Console.WriteLine();
        }
    }
}
class Program
{
    static void Main(string[] args)
    {
        // Load the workbook and access a specific worksheet
        WorkBook wb = WorkBook.Load("Weather.xlsx"); // Your Excel file Name
        WorkSheet ws = wb.GetWorkSheet("Sheet1");

        // Parse worksheet into datatable
        DataTable dt = ws.ToDataTable(true); // Parse Sheet1 of sample.xlsx file into DataTable

        // Iterate through rows and columns to display their values
        foreach (DataRow row in dt.Rows) // Access rows
        {
            for (int i = 0; i < dt.Columns.Count; i++) // Access columns of corresponding row
            {
                Console.Write(row[i] + "  ");
            }
            Console.WriteLine();
        }
    }
}
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Load the workbook and access a specific worksheet
		Dim wb As WorkBook = WorkBook.Load("Weather.xlsx") ' Your Excel file Name
		Dim ws As WorkSheet = wb.GetWorkSheet("Sheet1")

		' Parse worksheet into datatable
		Dim dt As DataTable = ws.ToDataTable(True) ' Parse Sheet1 of sample.xlsx file into DataTable

		' Iterate through rows and columns to display their values
		For Each row As DataRow In dt.Rows ' Access rows
			For i As Integer = 0 To dt.Columns.Count - 1 ' Access columns of corresponding row
				Console.Write(row(i) & "  ")
			Next i
			Console.WriteLine()
		Next row
	End Sub
End Class
$vbLabelText   $csharpLabel

C# 中讀取 CSV 檔案:教程,圖 4:DataTable 物件的控制台輸出 來自 DataTable 物件的控制台輸出

在這個例子中,我們將了解如何使用 Excel 檔案作為DataSet

class Program
{
    static void Main(string[] args)
    {
        // Load the workbook and convert it to a DataSet
        WorkBook wb = WorkBook.Load("sample.xlsx");
        DataSet ds = wb.ToDataSet(); // Parse WorkBook wb into DataSet

        // Iterate through tables to display their names
        foreach (DataTable dt in ds.Tables)
        {
            Console.WriteLine(dt.TableName);
        }
    }
}
class Program
{
    static void Main(string[] args)
    {
        // Load the workbook and convert it to a DataSet
        WorkBook wb = WorkBook.Load("sample.xlsx");
        DataSet ds = wb.ToDataSet(); // Parse WorkBook wb into DataSet

        // Iterate through tables to display their names
        foreach (DataTable dt in ds.Tables)
        {
            Console.WriteLine(dt.TableName);
        }
    }
}
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Load the workbook and convert it to a DataSet
		Dim wb As WorkBook = WorkBook.Load("sample.xlsx")
		Dim ds As DataSet = wb.ToDataSet() ' Parse WorkBook wb into DataSet

		' Iterate through tables to display their names
		For Each dt As DataTable In ds.Tables
			Console.WriteLine(dt.TableName)
		Next dt
	End Sub
End Class
$vbLabelText   $csharpLabel

C# 中讀取 CSV 檔案:教程,圖 5:從 DataSet 物件存取工作表名稱 從資料集物件存取工作表名稱

讓我們來看另一個例子,了解如何存取所有 Excel 工作表中每個儲存格的值。 在這裡,我們可以存取 Excel 檔案中每個工作表的每個儲存格的值。

class Program
{
    static void Main(string[] args)
    {
        // Load the workbook and convert it to a DataSet
        WorkBook wb = WorkBook.Load("Weather.xlsx");
        DataSet ds = wb.ToDataSet(); // Treat the complete Excel file as DataSet

        // Iterate through each table and its rows and columns
        foreach (DataTable dt in ds.Tables) // Treat Excel WorkSheet as DataTable
        {
            foreach (DataRow row in dt.Rows) // Corresponding Sheet's Rows
            {
                for (int i = 0; i < dt.Columns.Count; i++) // Sheet columns of corresponding row
                {
                    Console.Write(row[i] + "  ");
                }
                Console.WriteLine();
            }
        }
    }
}
class Program
{
    static void Main(string[] args)
    {
        // Load the workbook and convert it to a DataSet
        WorkBook wb = WorkBook.Load("Weather.xlsx");
        DataSet ds = wb.ToDataSet(); // Treat the complete Excel file as DataSet

        // Iterate through each table and its rows and columns
        foreach (DataTable dt in ds.Tables) // Treat Excel WorkSheet as DataTable
        {
            foreach (DataRow row in dt.Rows) // Corresponding Sheet's Rows
            {
                for (int i = 0; i < dt.Columns.Count; i++) // Sheet columns of corresponding row
                {
                    Console.Write(row[i] + "  ");
                }
                Console.WriteLine();
            }
        }
    }
}
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Load the workbook and convert it to a DataSet
		Dim wb As WorkBook = WorkBook.Load("Weather.xlsx")
		Dim ds As DataSet = wb.ToDataSet() ' Treat the complete Excel file as DataSet

		' Iterate through each table and its rows and columns
		For Each dt As DataTable In ds.Tables ' Treat Excel WorkSheet as DataTable
			For Each row As DataRow In dt.Rows ' Corresponding Sheet's Rows
				For i As Integer = 0 To dt.Columns.Count - 1 ' Sheet columns of corresponding row
					Console.Write(row(i) & "  ")
				Next i
				Console.WriteLine()
			Next row
		Next dt
	End Sub
End Class
$vbLabelText   $csharpLabel

C# 中讀取 CSV 檔案:教程,圖 6:資料集物件的控制台輸出 資料集物件的控制台輸出

5. C# .NET 中的 CSV 解析

CSV 檔案在欄位中處理換行符的方式上有大量問題,或者欄位可能包含在引號中,從而完全阻止簡單的字串分割方法。 最近,我發現使用 C# .NET 轉換 CSV 時,可以透過指定可自訂的分隔符號而不是使用string.Split(&#39;,&#39;)以逗號分隔值,來實現以下選項。

6. 在 C# 記錄中讀取 CSV 數據

此過程會將讀取器切換到下一個檔案。我們在 TryGetField 中讀取 CSV 欄位檔案。 我們使用讀取函數將 CSV 檔案中的欄位作為記錄欄位。

// Load a CSV file, specify the file format and delimiter
WorkBook workbook = WorkBook.LoadCSV("Weather.csv", fileFormat: ExcelFileFormat.XLSX, ListDelimiter: ",");

// Access the default worksheet from the workbook
WorkSheet ws = workbook.DefaultWorkSheet;

// Convert worksheet to DataTable    
DataTable dt = ws.ToDataTable(true); // Parse Sheet1 of sample.xlsx file into DataTable

// Iterate through rows and columns to display their values
foreach (DataRow row in dt.Rows) // Access rows
{
    for (int i = 0; i < dt.Columns.Count; i++) // Access columns of corresponding row
    {
        Console.Write(row[i] + "  ");
    }
    Console.WriteLine();
}
// Load a CSV file, specify the file format and delimiter
WorkBook workbook = WorkBook.LoadCSV("Weather.csv", fileFormat: ExcelFileFormat.XLSX, ListDelimiter: ",");

// Access the default worksheet from the workbook
WorkSheet ws = workbook.DefaultWorkSheet;

// Convert worksheet to DataTable    
DataTable dt = ws.ToDataTable(true); // Parse Sheet1 of sample.xlsx file into DataTable

// Iterate through rows and columns to display their values
foreach (DataRow row in dt.Rows) // Access rows
{
    for (int i = 0; i < dt.Columns.Count; i++) // Access columns of corresponding row
    {
        Console.Write(row[i] + "  ");
    }
    Console.WriteLine();
}
' Load a CSV file, specify the file format and delimiter
Dim workbook As WorkBook = WorkBook.LoadCSV("Weather.csv", fileFormat:= ExcelFileFormat.XLSX, ListDelimiter:= ",")

' Access the default worksheet from the workbook
Dim ws As WorkSheet = workbook.DefaultWorkSheet

' Convert worksheet to DataTable    
Dim dt As DataTable = ws.ToDataTable(True) ' Parse Sheet1 of sample.xlsx file into DataTable

' Iterate through rows and columns to display their values
For Each row As DataRow In dt.Rows ' Access rows
	For i As Integer = 0 To dt.Columns.Count - 1 ' Access columns of corresponding row
		Console.Write(row(i) & "  ")
	Next i
	Console.WriteLine()
Next row
$vbLabelText   $csharpLabel

C# 讀取 CSV 檔案教程,圖 7:DataTable 的控制台輸出 數據表的控制台輸出

7. 從 Excel 文件中取得數據

現在我們可以使用各種方法,輕鬆地從開啟的 Excel WorkSheet中取得任何類型的資料。 在以下範例中,我們可以看到如何存取特定單元格的值並將其解析為string

// Access the data by cell addressing
string val = ws["Cell Address"].ToString();
// Access the data by cell addressing
string val = ws["Cell Address"].ToString();
' Access the data by cell addressing
Dim val As String = ws("Cell Address").ToString()
$vbLabelText   $csharpLabel

在上面的程式碼中, wsWorkSheet ,它是在步驟 2 中定義的。這是一種"簡單"的方法,但您可以閱讀更多內容並查看存取 Excel 文件資料的不同範例。

8. 如何在 C# 中解析 Excel 文件

在使用 Excel 電子表格進行應用程式建置時,我們經常需要根據資料分析結果,並且需要在 C# 中將 Excel 檔案資料解析為所需的格式才能獲得正確的結果。 在 C# 環境中,使用 IronXL 可以輕鬆地將資料解析成不同的格式; 請參閱以下步驟。

using IronXL;

class Program
{
    static void Main(string[] args)
    {
        // Load the workbook and access a specific worksheet
        WorkBook wb = WorkBook.Load("sample.xlsx");
        WorkSheet ws = wb.GetWorkSheet("Sheet1");

        // Parse Excel cell value into string
        string str_val = ws["B3"].Value.ToString();

        // Parse Excel cell value into Int32
        Int32 int32_val = ws["G3"].Int32Value;

        // Parse Excel cell value into Decimal
        decimal decimal_val = ws["E5"].DecimalValue;

        // Output parsed values to the console
        Console.WriteLine("Parse B3 Cell Value into String: {0}", str_val);
        Console.WriteLine("Parse G3 Cell Value into Int32: {0}", int32_val);
        Console.WriteLine("Parse E5 Cell Value into decimal: {0}", decimal_val);

        Console.ReadKey();
    }
}
using IronXL;

class Program
{
    static void Main(string[] args)
    {
        // Load the workbook and access a specific worksheet
        WorkBook wb = WorkBook.Load("sample.xlsx");
        WorkSheet ws = wb.GetWorkSheet("Sheet1");

        // Parse Excel cell value into string
        string str_val = ws["B3"].Value.ToString();

        // Parse Excel cell value into Int32
        Int32 int32_val = ws["G3"].Int32Value;

        // Parse Excel cell value into Decimal
        decimal decimal_val = ws["E5"].DecimalValue;

        // Output parsed values to the console
        Console.WriteLine("Parse B3 Cell Value into String: {0}", str_val);
        Console.WriteLine("Parse G3 Cell Value into Int32: {0}", int32_val);
        Console.WriteLine("Parse E5 Cell Value into decimal: {0}", decimal_val);

        Console.ReadKey();
    }
}
Imports IronXL

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Load the workbook and access a specific worksheet
		Dim wb As WorkBook = WorkBook.Load("sample.xlsx")
		Dim ws As WorkSheet = wb.GetWorkSheet("Sheet1")

		' Parse Excel cell value into string
		Dim str_val As String = ws("B3").Value.ToString()

		' Parse Excel cell value into Int32
		Dim int32_val As Int32 = ws("G3").Int32Value

		' Parse Excel cell value into Decimal
		Dim decimal_val As Decimal = ws("E5").DecimalValue

		' Output parsed values to the console
		Console.WriteLine("Parse B3 Cell Value into String: {0}", str_val)
		Console.WriteLine("Parse G3 Cell Value into Int32: {0}", int32_val)
		Console.WriteLine("Parse E5 Cell Value into decimal: {0}", decimal_val)

		Console.ReadKey()
	End Sub
End Class
$vbLabelText   $csharpLabel

9. 如何將Excel資料解析為數值和布林值

現在我們來學習如何解析Excel檔案資料。 首先,讓我們來看看如何處理 Excel 中的數值數據,然後看看如何將其解析成我們所需的格式。

C# 中讀取 CSV 檔案:教程,圖 8:每種資料類型的總表 每種資料類型的總計表

class Program
{
    static void Main(string[] args)
    {
        // Load the workbook and access a specific worksheet
        WorkBook wb = WorkBook.Load("sample.xlsx");
        WorkSheet ws = wb.GetWorkSheet("Sheet1");

        // Parse Excel cell value into string
        string str_val = ws["B3"].Value.ToString();

        // Parse Excel cell value into Int32
        Int32 int32_val = ws["G3"].Int32Value;

        // Parse Excel cell value into Decimal
        decimal decimal_val = ws["E5"].DecimalValue;

        // Output parsed values to the console
        Console.WriteLine("Parse B3 Cell Value into String: {0}", str_val);
        Console.WriteLine("Parse G3 Cell Value into Int32: {0}", int32_val);
        Console.WriteLine("Parse E5 Cell Value into decimal: {0}", decimal_val);

        Console.ReadKey();
    }
}
class Program
{
    static void Main(string[] args)
    {
        // Load the workbook and access a specific worksheet
        WorkBook wb = WorkBook.Load("sample.xlsx");
        WorkSheet ws = wb.GetWorkSheet("Sheet1");

        // Parse Excel cell value into string
        string str_val = ws["B3"].Value.ToString();

        // Parse Excel cell value into Int32
        Int32 int32_val = ws["G3"].Int32Value;

        // Parse Excel cell value into Decimal
        decimal decimal_val = ws["E5"].DecimalValue;

        // Output parsed values to the console
        Console.WriteLine("Parse B3 Cell Value into String: {0}", str_val);
        Console.WriteLine("Parse G3 Cell Value into Int32: {0}", int32_val);
        Console.WriteLine("Parse E5 Cell Value into decimal: {0}", decimal_val);

        Console.ReadKey();
    }
}
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Load the workbook and access a specific worksheet
		Dim wb As WorkBook = WorkBook.Load("sample.xlsx")
		Dim ws As WorkSheet = wb.GetWorkSheet("Sheet1")

		' Parse Excel cell value into string
		Dim str_val As String = ws("B3").Value.ToString()

		' Parse Excel cell value into Int32
		Dim int32_val As Int32 = ws("G3").Int32Value

		' Parse Excel cell value into Decimal
		Dim decimal_val As Decimal = ws("E5").DecimalValue

		' Output parsed values to the console
		Console.WriteLine("Parse B3 Cell Value into String: {0}", str_val)
		Console.WriteLine("Parse G3 Cell Value into Int32: {0}", int32_val)
		Console.WriteLine("Parse E5 Cell Value into decimal: {0}", decimal_val)

		Console.ReadKey()
	End Sub
End Class
$vbLabelText   $csharpLabel

這段程式碼將顯示以下輸出:

C# 中讀取 CSV 檔案:教程,圖 9:具有正確資料類型的控制台輸出 控制台輸出包含正確的資料類型

我們可以在這裡看到Excel檔案sample.xlsx的值:

C# 讀取 CSV 檔案教程,圖 10:在 Excel 中顯示正確的資料類型 在 Excel 中顯示正確的資料類型

IronXL 提供了BoolValue函數,用於將 Excel 檔案資料解析為布林資料類型。 它的用法如下:

// Access a cell value as a boolean
bool Val = ws["Cell Address"].BoolValue;
// Access a cell value as a boolean
bool Val = ws["Cell Address"].BoolValue;
' Access a cell value as a boolean
Dim Val As Boolean = ws("Cell Address").BoolValue
$vbLabelText   $csharpLabel

10. 如何將 Excel 檔案解析為 C# 集合

class Program
{
    static void Main(string[] args)
    {
        // Load the workbook and access a specific worksheet
        WorkBook wb = WorkBook.Load("sample.xlsx");
        WorkSheet ws = wb.GetWorkSheet("Sheet1");

        // Convert a range into an array
        var array = ws["B6:F6"].ToArray();

        // Get the count of items in the array
        int item = array.Count();

        // Get the first item as a string
        string total_items = array[0].Value.ToString();

        // Output information about the array to the console
        Console.WriteLine("First item in the array: {0}", item);
        Console.WriteLine("Total items from B6 to F6: {0}", total_items);

        Console.ReadKey();
    }
}
class Program
{
    static void Main(string[] args)
    {
        // Load the workbook and access a specific worksheet
        WorkBook wb = WorkBook.Load("sample.xlsx");
        WorkSheet ws = wb.GetWorkSheet("Sheet1");

        // Convert a range into an array
        var array = ws["B6:F6"].ToArray();

        // Get the count of items in the array
        int item = array.Count();

        // Get the first item as a string
        string total_items = array[0].Value.ToString();

        // Output information about the array to the console
        Console.WriteLine("First item in the array: {0}", item);
        Console.WriteLine("Total items from B6 to F6: {0}", total_items);

        Console.ReadKey();
    }
}
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Load the workbook and access a specific worksheet
		Dim wb As WorkBook = WorkBook.Load("sample.xlsx")
		Dim ws As WorkSheet = wb.GetWorkSheet("Sheet1")

		' Convert a range into an array
		Dim array = ws("B6:F6").ToArray()

		' Get the count of items in the array
		Dim item As Integer = array.Count()

		' Get the first item as a string
		Dim total_items As String = array(0).Value.ToString()

		' Output information about the array to the console
		Console.WriteLine("First item in the array: {0}", item)
		Console.WriteLine("Total items from B6 to F6: {0}", total_items)

		Console.ReadKey()
	End Sub
End Class
$vbLabelText   $csharpLabel

10.1 如何將 Excel WorkSheet解析為資料表

IronXL 的一個出色功能是我們可以輕鬆地將特定的 Excel WorkSheet轉換為資料表。 為此,我們可以使用 IronXL 的.ToDataTable()函數,如下所示:

class Program
{
    static void Main(string[] args)
    {
        // Load the workbook and access a specific worksheet
        WorkBook wb = WorkBook.Load("sample.xlsx");
        WorkSheet ws = wb.GetWorkSheet("Sheet1");

        // Parse Sheet1 of sample.xlsx file into DataTable
        // Setting 'true' makes the first row in Excel as the column names in DataTable
        DataTable dt = ws.ToDataTable(true);
    }
}
class Program
{
    static void Main(string[] args)
    {
        // Load the workbook and access a specific worksheet
        WorkBook wb = WorkBook.Load("sample.xlsx");
        WorkSheet ws = wb.GetWorkSheet("Sheet1");

        // Parse Sheet1 of sample.xlsx file into DataTable
        // Setting 'true' makes the first row in Excel as the column names in DataTable
        DataTable dt = ws.ToDataTable(true);
    }
}
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Load the workbook and access a specific worksheet
		Dim wb As WorkBook = WorkBook.Load("sample.xlsx")
		Dim ws As WorkSheet = wb.GetWorkSheet("Sheet1")

		' Parse Sheet1 of sample.xlsx file into DataTable
		' Setting 'true' makes the first row in Excel as the column names in DataTable
		Dim dt As DataTable = ws.ToDataTable(True)
	End Sub
End Class
$vbLabelText   $csharpLabel

10.2 如何將 Excel 檔案解析為資料集

如果我們想要將完整的 Excel 檔案解析為 DataSet,那麼為此我們可以使用 IronXL 中的.ToDataSet()函數。

class Program
{
    static void Main(string[] args)
    {
        // Load an entire workbook into a DataSet
        WorkBook wb = WorkBook.Load("sample.xlsx");

        // Convert workbook to DataSet
        DataSet ds = wb.ToDataSet();

        // We can also get a DataTable from the DataSet which corresponds to a WorkSheet
        DataTable dt = ds.Tables[0];
    }
}
class Program
{
    static void Main(string[] args)
    {
        // Load an entire workbook into a DataSet
        WorkBook wb = WorkBook.Load("sample.xlsx");

        // Convert workbook to DataSet
        DataSet ds = wb.ToDataSet();

        // We can also get a DataTable from the DataSet which corresponds to a WorkSheet
        DataTable dt = ds.Tables[0];
    }
}
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Load an entire workbook into a DataSet
		Dim wb As WorkBook = WorkBook.Load("sample.xlsx")

		' Convert workbook to DataSet
		Dim ds As DataSet = wb.ToDataSet()

		' We can also get a DataTable from the DataSet which corresponds to a WorkSheet
		Dim dt As DataTable = ds.Tables(0)
	End Sub
End Class
$vbLabelText   $csharpLabel

10.3 讀取特定範圍內的 Excel 數據

IronXL 提供了一種智慧方法來讀取特定範圍內的 Excel 檔案資料。 此範圍可以應用於行和列。

class Program
{
    static void Main(string[] args)
    {
        // Load the workbook and access a specific worksheet
        WorkBook wb = WorkBook.Load("sample.xlsx");
        WorkSheet ws = wb.GetWorkSheet("Sheet1");

        // Get specified range values by loop
        foreach (var item in ws["B3:B8"])
        {
            Console.WriteLine("Value is: {0}", item);
        }
        Console.ReadKey();
    }
}
class Program
{
    static void Main(string[] args)
    {
        // Load the workbook and access a specific worksheet
        WorkBook wb = WorkBook.Load("sample.xlsx");
        WorkSheet ws = wb.GetWorkSheet("Sheet1");

        // Get specified range values by loop
        foreach (var item in ws["B3:B8"])
        {
            Console.WriteLine("Value is: {0}", item);
        }
        Console.ReadKey();
    }
}
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Load the workbook and access a specific worksheet
		Dim wb As WorkBook = WorkBook.Load("sample.xlsx")
		Dim ws As WorkSheet = wb.GetWorkSheet("Sheet1")

		' Get specified range values by loop
		For Each item In ws("B3:B8")
			Console.WriteLine("Value is: {0}", item)
		Next item
		Console.ReadKey()
	End Sub
End Class
$vbLabelText   $csharpLabel

上述程式碼顯示以下輸出:

C# 讀取 CSV 檔案教學,圖 11:控制台輸出,存取 B3:B8 範圍內的所有值 控制台輸出以存取 B3:B8 範圍內的所有值

並產生 Excel 檔案 sample.xlsx 中的值:

C# 讀取 CSV 檔案教學,圖 12:範例檔案 sample.xlsx 的資料展示 範例檔案 sample.xlsx 的資料展示

此外,IronXL 還相容於許多 Excel 方法,可用於與儲存格交互,包括樣式和邊框數學函數條件格式或根據可用資料建立圖表。

11. 如何讀取 Excel 檔案中的布林數據

在應用程式開發中,我們需要根據 Excel 文件中的布林資料類型做出決策。

class Program
{
    static void Main(string[] args)
    {
        // Load the workbook and access a specific worksheet
        WorkBook wb = WorkBook.Load("sample.xlsx");
        WorkSheet ws = wb.GetWorkSheet("Sheet1");

        // Traverse a range and output boolean values
        foreach (var item in ws["G1:G10"])
        {
            Console.WriteLine("Condition is: {0}", item.BoolValue);
        }
        Console.ReadKey();
    }
}
class Program
{
    static void Main(string[] args)
    {
        // Load the workbook and access a specific worksheet
        WorkBook wb = WorkBook.Load("sample.xlsx");
        WorkSheet ws = wb.GetWorkSheet("Sheet1");

        // Traverse a range and output boolean values
        foreach (var item in ws["G1:G10"])
        {
            Console.WriteLine("Condition is: {0}", item.BoolValue);
        }
        Console.ReadKey();
    }
}
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Load the workbook and access a specific worksheet
		Dim wb As WorkBook = WorkBook.Load("sample.xlsx")
		Dim ws As WorkSheet = wb.GetWorkSheet("Sheet1")

		' Traverse a range and output boolean values
		For Each item In ws("G1:G10")
			Console.WriteLine("Condition is: {0}", item.BoolValue)
		Next item
		Console.ReadKey()
	End Sub
End Class
$vbLabelText   $csharpLabel

由此,我們得到以下輸出:

C# 讀取 CSV 檔案教程,圖 13:取得布林資料的控制台輸出 取得布林資料時的控制台輸出

Excel 檔案 sample.xlsx,其中包含 C1 到 C10 的值:

C# 中讀取 CSV 檔案:教程,圖 14:Excel 範例,可與控制台輸出進行比較 用於與控制台輸出進行比較的 Excel 範例

12. 如何閱讀完整的Excel工作表

利用行和列索引可以輕鬆讀取完整的 Excel 工作表。 為此,我們使用兩個循環:一個用於遍歷所有行,另一個用於遍歷特定行的所有列。 這樣我們就可以輕鬆取得整個 Excel 工作表中所有儲存格的值。

class Program
{
    static void Main(string[] args)
    {
        // Load the workbook and access a specific worksheet
        WorkBook wb = WorkBook.Load("Weather.xlsx"); // Your Excel File Name
        WorkSheet ws = wb.GetWorkSheet("Sheet1");

        // Traverse all rows of Excel WorkSheet
        for (int i = 0; i < ws.Rows.Count(); i++)
        {
            // Traverse all columns of specific Row
            for (int j = 0; j < ws.Columns.Count(); j++)
            {
                // Get the values
                string val = ws.Rows[i].Columns[j].Value.ToString();
                Console.WriteLine("Value of Row {0} and Column {1} is: {2}", i, j, val);
            }
        }
        Console.ReadKey();
    }
}
class Program
{
    static void Main(string[] args)
    {
        // Load the workbook and access a specific worksheet
        WorkBook wb = WorkBook.Load("Weather.xlsx"); // Your Excel File Name
        WorkSheet ws = wb.GetWorkSheet("Sheet1");

        // Traverse all rows of Excel WorkSheet
        for (int i = 0; i < ws.Rows.Count(); i++)
        {
            // Traverse all columns of specific Row
            for (int j = 0; j < ws.Columns.Count(); j++)
            {
                // Get the values
                string val = ws.Rows[i].Columns[j].Value.ToString();
                Console.WriteLine("Value of Row {0} and Column {1} is: {2}", i, j, val);
            }
        }
        Console.ReadKey();
    }
}
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Load the workbook and access a specific worksheet
		Dim wb As WorkBook = WorkBook.Load("Weather.xlsx") ' Your Excel File Name
		Dim ws As WorkSheet = wb.GetWorkSheet("Sheet1")

		' Traverse all rows of Excel WorkSheet
		For i As Integer = 0 To ws.Rows.Count() - 1
			' Traverse all columns of specific Row
			For j As Integer = 0 To ws.Columns.Count() - 1
				' Get the values
				Dim val As String = ws.Rows(i).Columns(j).Value.ToString()
				Console.WriteLine("Value of Row {0} and Column {1} is: {2}", i, j, val)
			Next j
		Next i
		Console.ReadKey()
	End Sub
End Class
$vbLabelText   $csharpLabel

C# 中讀取 CSV 檔案:教程,圖 15:讀取所有值後的控制台輸出 讀取所有值的控制台輸出

13. 如何在不使用互通的情況下讀取 Excel 文件

IronXL 是一個適用於 C# 和 .NET 的 Excel 程式庫,它允許開發人員無需使用 Microsoft.Office.Interop.Excel 即可XLS 和 XLSX文件讀取和編輯 Excel 資料。

該 API 使我們能夠直觀地創建、讀取、操作、保存和匯出 Excel 文件,用於:

  1. .NET Framework 4.5+
  2. .NET Core 2+
  3. .NET 標準
  4. Xamarin
  5. Windows Mobile
  6. 單聲道
  7. 和 Azure 雲端託管
  8. Blazor
  9. .NET 版本

新增下列名稱空間:

using IronXL;
using System;
using System.Linq;
using IronXL;
using System;
using System.Linq;
Imports IronXL
Imports System
Imports System.Linq
$vbLabelText   $csharpLabel

現在在主函數中編寫以下程式碼。

class Program
{
    static void Main(string[] args)
    {
        // Load an Excel file and access the first worksheet
        WorkBook workbook = WorkBook.Load("Weather.xlsx");
        WorkSheet sheet = workbook.WorkSheets.First();

        // Select cells easily in Excel notation and return the calculated value
        int cellValue = sheet["A2"].IntValue;

        // Read from ranges of cells elegantly
        foreach (var cell in sheet["A2:A10"])
        {
            Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text);
        }
    }
}
class Program
{
    static void Main(string[] args)
    {
        // Load an Excel file and access the first worksheet
        WorkBook workbook = WorkBook.Load("Weather.xlsx");
        WorkSheet sheet = workbook.WorkSheets.First();

        // Select cells easily in Excel notation and return the calculated value
        int cellValue = sheet["A2"].IntValue;

        // Read from ranges of cells elegantly
        foreach (var cell in sheet["A2:A10"])
        {
            Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text);
        }
    }
}
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Load an Excel file and access the first worksheet
		Dim workbook As WorkBook = WorkBook.Load("Weather.xlsx")
		Dim sheet As WorkSheet = workbook.WorkSheets.First()

		' Select cells easily in Excel notation and return the calculated value
		Dim cellValue As Integer = sheet("A2").IntValue

		' Read from ranges of cells elegantly
		For Each cell In sheet("A2:A10")
			Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text)
		Next cell
	End Sub
End Class
$vbLabelText   $csharpLabel

C# 讀取 CSV 檔案教程,圖 16:每個單元格的控制台輸出 每個單元格的控制台輸出

IronXL 也完全支援 ASP.NET、MVC、Windows、macOS、Linux、iOS 和 Android 行動應用程式開發。

14. 結論和 Iron XL 特別優惠

除了在 C# 中解析 CSV 檔案外,IronXL 只需兩行程式碼即可將 CSV 檔案轉換為 Excel 檔案!

使用 C# 或 VB.NET,無需互通即可輕鬆使用 IronXL 的 Excel API。您可以讀取、編輯和建立 Excel 電子表格,或處理其他 Excel 格式,例如XLS/XLSX/CSV/TSV 。 透過多種框架的支持,您可以花兩件產品的價格購買五件產品。 點擊我們的定價頁面以了解更多資訊。

C# 中讀取 CSV 檔案:教程,圖 17:Iron Suite 的 5 個產品 Iron Suite 的 5 款產品

常見問題解答

如何在 C# 中讀取 CSV 檔案?

若要在 C# 中讀取 CSV 檔案,您可以透過 Visual Studio 中的 NuGet 安裝函式庫來使用 IronXL。安裝完成後,使用 WorkBook.LoadCSV 方法載入並解譯 CSV 檔案。

什麼是 CSV?為什麼在 C# 中處理 CSV 會很複雜?

CSV 是一種簡單的資料格式,但由於分隔符不同,處理起來可能會很複雜。IronXL 可簡化 C# 專案中 CSV 檔案的讀取與解析。

我可以使用 C# 將 CSV 檔案轉換為 Excel 嗎?

是的,IronXL 允許您透過載入 CSV 並使用 WorkBook.SaveAs 方法儲存,將 CSV 檔案轉換為 Excel 格式,如 XLS 或 XLSX。

如何在 C# 專案中安裝 IronXL?

您可以使用 Visual Studio 中的 NuGet Package Manager 安裝 IronXL。搜尋「IronXL.Excel」並將其新增至您的專案,即可開始處理 Excel 檔案。

是否可以在 C# 中將 Excel 單元格資料解析為特定的資料類型?

是的,使用 IronXL,您可以使用 Int32ValueBoolValue 等方法將 Excel 單元格值解析為特定的資料類型,例如數值和布林。

如何使用 C# 從 Excel 表單中的特定儲存格範圍讀取資料?

使用 IronXL,您可以透過循環迭代範圍讀取特定儲存格中的資料,並透過 IronXL 的索引功能存取儲存格值。

如何在 C# 中將 Excel 工作表轉換為 DataTable?

您可以使用 IronXL.Excel 的 WorkSheet.ToDataTable 方法將 Excel 工作表轉換為 DataTable,該方法可將工作表有效地解析為 DataTable 物件,以便進行資料處理。

我需要 Microsoft Office Interop 來以程式化方式讀取 Excel 檔案嗎?

不,使用 IronXL.Excel,您不需要 Microsoft Office Interop 即可讀取和處理 Excel 檔案,使其成為獨立且高效的解決方案。

使用 IronXL.Excel 處理 Excel 和 CSV 檔案有哪些優點?

IronXL 提供簡易安裝、不需依賴 Interop、支援多種 Excel 格式,並與各種 .NET Framework 相容,可提高處理 CSV 和 Excel 檔案的生產力。

如何用 C# 閱讀完整的 Excel 工作表?

若要使用 IronXL 讀取完整的 Excel 工作表,您可以使用嵌套循環遍歷所有的行和列,並使用 IronXL 的方法擷取儲存格數值。

Jordi Bardia
軟體工程師
Jordi 在 Python、C# 和 C++ 上最得心應手,當他不在 Iron Software 展現技術時,便在做遊戲編程。在分担产品测测试,产品开发和研究的责任时,Jordi 为持续的产品改进增值。他说这种多样化的经验使他受到挑战并保持参与, 而这也是他与 Iron Software 中工作一大乐趣。Jordi 在佛罗里达州迈阿密长大,曾在佛罗里达大学学习计算机科学和统计学。