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

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

工作在不同的 Excel 格式上經常需要讀取數據,然後以程式化方式重新配置它。 在本文中,我們將學習如何使用 IronXL 在 C# 中讀取 CSV 文件和解析 Excel 試算表中的數據,這是完成此工作的完美工具。

什麼是 CSV?

CSV 是一個簡單的數據格式,但可能會有很多差異; 在我們的 C# 項目中,因為它使用多個分隔符來區分數據的行和列,所以程式化讀取可能會很困難。 本文將向您展示如何使用 IronXL 庫 讀取 CSV 文件。


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

在您可以利用 IronXL 在 MVC、ASP.NET 或 .NET Core 中讀取 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

輸出:

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

代碼解釋:

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

然後創建了一個 WorkSheet 對象。 這就是 CSV 文件內容會放置的地方。 文件以新名稱和格式保存。

在 C# 中讀取 CSV 文件:教程,圖 3:Microsoft Excel 中顯示的數據 Microsoft Excel 中顯示的數據


2. IronXL 用於 Excel 文件

使用 IronXL 作為專案的精簡方式來在 C# 中處理 Excel 文件格式。 您可以直接下載安裝 IronXL。 或者,您可以使用Visual Studio 的 NuGet 安裝。 該軟體是免費供開發使用。

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 工作表作為 DataTable 讀取

使用 IronXL,將 Excel WorkSheet 作為 DataTable 進行操作非常簡單。

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 對象訪問表名 從 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(',') 來按逗號分隔值。

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 的控制台輸出 來自 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

在上面的行中,ws 是在第 2 步中定義的 WorkSheet。這是'簡單的'方法,但您可以閱讀更多並查看不同示例以瞭解如何訪問 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 中顯示正確的數據類型

為了將 Excel 文件數據解析為布林數據類型,IronXL 提供了 BoolValue 函數。 它可以如下使用:

// 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 解析到 DataTable

IronXL 的一個優秀功能是我們可以輕鬆地將特定 Excel WorkSheet 轉換為 DataTable。 為此,我們可以使用 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 文件解析到 DataSet

如果我們想將完整的 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 的數據顯示

Additionally, IronXL is also compatible with many Excel methods to interact with cells including styling and border, math functions, conditional formatting or creating charts from available data.

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. 如何在不使用 Interop 的情況下讀取 Excel 文件

IronXL 是一個Excel 庫為 C#和 .NET,其允許開發人員從XLS 和 XLSX文檔中讀取和編輯 Excel 數據無需使用 Microsoft.Office.Interop.Excel

API 允許我們直觀地創建、讀取、操作、保存和導出 Excel 文件,支持:

  1. .NET Framework 4.5+
  2. .NET Core 2+
  3. .NET Standard
  4. Xamarin
  5. Windows Mobile
  6. Mono
  7. & Azure 雲端託管
  8. Blazor
  9. .NET MAUI

添加以下命名空間:

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 非常簡單無需使用 Interop。您可以讀取、編輯和創建 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 是一種簡單的數據格式,但由於定界符的變化,處理起來可能很複雜。IronXL 簡化了 C# 項目中 CSV 文件的讀取和解析。

我可以使用 C# 將 CSV 文件轉換為 Excel 嗎?

是的,IronXL 允許您通過加載 CSV 並使用 WorkBook.SaveAs 方法保存它來將 CSV 文件轉換為 XLS 或 XLSX 等 Excel 格式。

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

您可以使用 Visual Studio 中的 NuGet 套件管理器安裝 IronXL。搜尋 'IronXL.Excel' 並將其添加到您的專案以開始使用 Excel 文件。

是否可以在 C# 中解析 Excel 單元格數據到特定的數據類型?

是的,使用 IronXL,您可以通過使用 Int32ValueBoolValue 等方法解析 Excel 單元格值為特定數據類型,如數值和布爾型。

如何使用 C# 從 Excel 工作表的特定範圍中讀取數據?

使用 IronXL,您可以通過循環迭代特定範圍並通過 IronXL 的索引能力訪問單元格值來讀取特定單元格的數據。

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

您可以使用 IronXL 的 WorkSheet.ToDataTable 方法將 Excel 工作表轉換為 DataTable,該方法能夠將工作表解析為 DataTable 對象以進行數據操作。

我是否需要 Microsoft Office Interop 來程式化地讀取 Excel 文件?

不需要,使用 IronXL,您可以無需 Microsoft Office Interop 讀取和操作 Excel 文件,使其成為一個獨立且高效的解決方案。

使用 IronXL 處理 Excel 和 CSV 文件有什麼優勢?

IronXL 提供便捷安裝、無需依賴 Interop、支持多種 Excel 格式,與各種 .NET 框架兼容,提高處理 CSV 和 Excel 文件的效率。

如何在 C# 中讀取完整的 Excel 工作表?

要使用 IronXL 讀取完整的 Excel 工作表,您可以使用嵌套循環遍歷所有行和列,並通過 IronXL 的方法提取單元格值。

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