使用IRONXL

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

已更新 2024年1月6日
分享:

處理各種 Excel 格式通常需要讀取數據,然後以編程方式重新配置。 在本文中,我們將學習如何使用IronXL在C#中讀取CSV文件和解析Excel電子表格中的數據,這是完成此工作的理想工具。

什麼是CSV?

CSV 是一種簡單的數據格式,但在我們的 C# 專案中,程式上讀取 CSV 可能很困難,因為它使用多種分隔符來區分資料的行和列,這之間會有很多不同之處。 本文將向您展示如何使用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 檔案,如下面的代碼片段所示。

WorkBook workbook = WorkBook.LoadCSV("Weather.csv", fileFormat: ExcelFileFormat.XLSX, ListDelimiter: ",");
WorkSheet ws = workbook.DefaultWorkSheet;
workbook.SaveAs("Csv_To_Excel.xlsx");
WorkBook workbook = WorkBook.LoadCSV("Weather.csv", fileFormat: ExcelFileFormat.XLSX, ListDelimiter: ",");
WorkSheet ws = workbook.DefaultWorkSheet;
workbook.SaveAs("Csv_To_Excel.xlsx");
Dim workbook As WorkBook = WorkBook.LoadCSV("Weather.csv", fileFormat:= ExcelFileFormat.XLSX, ListDelimiter:= ",")
Dim ws As WorkSheet = workbook.DefaultWorkSheet
workbook.SaveAs("Csv_To_Excel.xlsx")
VB   C#

輸出:

在C#中讀取CSV檔案:教學,第2圖:使用逗號分隔符的輸出CSV檔案

輸出使用逗號分隔的 CSV 檔案

程式碼解釋:

AWorkbook物件已創建。 這LoadCSV接著使用WorkBook物件的方法來指定CSV的名稱及其格式,以及在讀取的CSV文件中使用的分隔符。 在這種情況下,逗號用作分隔符。

A工作表然後創建對象。 這是將放置 CSV 檔案內容的地方。 然後將檔案以新的名稱和格式儲存。

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

顯示在Microsoft Excel中的數據


2. IronXL 支援 Excel 文件

使用 IronXL 為您的專案提供一個簡化方式來處理 C# 中的 Excel 檔案格式。 您可以选择通過直接下載安裝 IronXL. 或者,您可以使用Visual Studio 的 NuGet 安裝. 該軟體可免費用於開發。

Install-Package IronXL.Excel

3. 加載 WorkBook 並訪問 WorkSheet

WorkBook 是 IronXL 的類別,其對象提供對 Excel 文件及其所有功能的完整訪問。 例如,如果我們想要存取 Excel 檔案,我們會使用以下代碼:

WorkBook wb = WorkBook.Load("sample.xlsx");//Excel file path
WorkBook wb = WorkBook.Load("sample.xlsx");//Excel file path
Dim wb As WorkBook = WorkBook.Load("sample.xlsx") 'Excel file path
VB   C#

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

WorkSheet ws = wb.GetWorkSheet("Sheet1"); //by sheet name
WorkSheet ws = wb.GetWorkSheet("Sheet1"); //by sheet name
Dim ws As WorkSheet = wb.GetWorkSheet("Sheet1") 'by sheet name
VB   C#

一旦獲得 Excel 工作表 ws,您可以從中提取任何類型的數據並執行所有的 Excel 功能。 在此過程中,可以從 Excel 工作表 ws 中存取資料:

using IronXL;
static void Main(string [] args)
{
    WorkBook wb = WorkBook.Load("sample.xlsx");
    WorkSheet ws = wb.GetWorkSheet("Sheet1");
    foreach (var cell in ws ["A2:A10"])
    {
        Console.WriteLine("value is: {0}", cell.Text);
    }
    Console.ReadKey();
}
using IronXL;
static void Main(string [] args)
{
    WorkBook wb = WorkBook.Load("sample.xlsx");
    WorkSheet ws = wb.GetWorkSheet("Sheet1");
    foreach (var cell in ws ["A2:A10"])
    {
        Console.WriteLine("value is: {0}", cell.Text);
    }
    Console.ReadKey();
}
Imports IronXL
Shared Sub Main(ByVal args() As String)
	Dim wb As WorkBook = WorkBook.Load("sample.xlsx")
	Dim ws As WorkSheet = wb.GetWorkSheet("Sheet1")
	For Each cell In ws ("A2:A10")
		Console.WriteLine("value is: {0}", cell.Text)
	Next cell
	Console.ReadKey()
End Sub
VB   C#

4. 將 Excel 工作表讀取為 DataTable

使用IronXL,操作Excel的WorkSheet作為DataTable非常簡單。

DataTable dt = WorkSheet.ToDataTable();
DataTable dt = WorkSheet.ToDataTable();
Dim dt As DataTable = WorkSheet.ToDataTable()
VB   C#

使用以下命名空間

using IronXL;
using System.Data;
using IronXL;
using System.Data;
Imports IronXL
Imports System.Data
VB   C#

撰寫以下代碼:

static void Main(string [] args)
{
    WorkBook wb = WorkBook.Load("Weather.xlsx"); // Your Excel file Name
    WorkSheet ws = wb.GetWorkSheet("Sheet1");
    DataTable dt = ws.ToDataTable(true);//parse sheet1 of sample.xlsx file into datatable
    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();
    }
}
static void Main(string [] args)
{
    WorkBook wb = WorkBook.Load("Weather.xlsx"); // Your Excel file Name
    WorkSheet ws = wb.GetWorkSheet("Sheet1");
    DataTable dt = ws.ToDataTable(true);//parse sheet1 of sample.xlsx file into datatable
    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();
    }
}
Shared Sub Main(ByVal args() As String)
	Dim wb As WorkBook = WorkBook.Load("Weather.xlsx") ' Your Excel file Name
	Dim ws As WorkSheet = wb.GetWorkSheet("Sheet1")
	Dim dt As DataTable = ws.ToDataTable(True) 'parse sheet1 of sample.xlsx file into datatable
	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
VB   C#

在C#中讀取CSV檔案:教學,圖4:從DataTable物件獲取的控制台輸出

DataTable 對象的控制臺輸出

在此示例中,我們將查看如何使用 Excel 文件作為 DataSet

static void Main(string [] args)
{          
    WorkBook wb = WorkBook.Load("sample.xlsx");
    DataSet ds = wb.ToDataSet(); //Parse WorkBook wb into DataSet
    foreach (DataTable dt in ds.Tables)
    {
        Console.WriteLine(dt.TableName);
    }
}
static void Main(string [] args)
{          
    WorkBook wb = WorkBook.Load("sample.xlsx");
    DataSet ds = wb.ToDataSet(); //Parse WorkBook wb into DataSet
    foreach (DataTable dt in ds.Tables)
    {
        Console.WriteLine(dt.TableName);
    }
}
Shared Sub Main(ByVal args() As String)
	Dim wb As WorkBook = WorkBook.Load("sample.xlsx")
	Dim ds As DataSet = wb.ToDataSet() 'Parse WorkBook wb into DataSet
	For Each dt As DataTable In ds.Tables
		Console.WriteLine(dt.TableName)
	Next dt
End Sub
VB   C#

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

從 DataSet 物件中存取工作表名稱

讓我們看看另一個範例,如何存取所有 Excel 工作表中的每一個儲存格值。 在這裡,我們可以存取 Excel 文件中每個工作表的每個單元格的值。

static void Main(string [] args)
{
    WorkBook wb = WorkBook.Load("Weather.xlsx");
    DataSet ds = wb.ToDataSet();//behave complete Excel file as DataSet
    foreach (DataTable dt in ds.Tables)//behave 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();
        }
    }
}
static void Main(string [] args)
{
    WorkBook wb = WorkBook.Load("Weather.xlsx");
    DataSet ds = wb.ToDataSet();//behave complete Excel file as DataSet
    foreach (DataTable dt in ds.Tables)//behave 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();
        }
    }
}
Shared Sub Main(ByVal args() As String)
	Dim wb As WorkBook = WorkBook.Load("Weather.xlsx")
	Dim ds As DataSet = wb.ToDataSet() 'behave complete Excel file as DataSet
	For Each dt As DataTable In ds.Tables 'behave 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
VB   C#

在 C# 中讀取 CSV 檔案:教程,圖 6:Dataset 對象的控制台輸出

Dataset 對象的控制台輸出

5. 在 C# .NET 中解析 CSV

CSV 有大量關於如何處理欄位中的換行符,以及如何將欄位包含在引號中的問題,這使得簡單的字串分割方法無法使用。 我最近發現可以在C# .NET中轉換CSV時透過指定可自訂的分隔符來取代使用string.Split的下列選項:(',')` 用逗號分隔數值。

6. 在 C# 中读取 CSV 数据记录

此過程使讀者進入下一個檔案。我們在 trygetfield 中讀取 CSV 欄位檔案。 我們將 CSV 文件的欄位使用讀取功能作為記錄欄位。

WorkBook workbook = WorkBook.LoadCSV("Weather.csv", fileFormat: ExcelFileFormat.XLSX, ListDelimiter: ",");
WorkSheet ws = workbook.DefaultWorkSheet;
DataTable dt = ws.ToDataTable(true);//parse sheet1 of sample.xlsx file into datatable
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();
}
WorkBook workbook = WorkBook.LoadCSV("Weather.csv", fileFormat: ExcelFileFormat.XLSX, ListDelimiter: ",");
WorkSheet ws = workbook.DefaultWorkSheet;
DataTable dt = ws.ToDataTable(true);//parse sheet1 of sample.xlsx file into datatable
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();
}
Dim workbook As WorkBook = WorkBook.LoadCSV("Weather.csv", fileFormat:= ExcelFileFormat.XLSX, ListDelimiter:= ",")
Dim ws As WorkSheet = workbook.DefaultWorkSheet
Dim dt As DataTable = ws.ToDataTable(True) 'parse sheet1 of sample.xlsx file into datatable
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
VB   C#

在 C# 中讀取 CSV 文件:教程,圖 7:來自 DataTable 的控制台輸出

DataTable 的控制台輸出

7. 從 Excel 文件獲取數據

現在我們可以輕鬆地使用各種方法從開放的 Excel 工作表獲取任何類型的數據。 在以下範例中,我們可以看到如何訪問特定的單元格值並將其解析為 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()
VB   C#

在上面的行中,ws 是在步驟 2 中定義的工作表。這是「簡單」的方法,但您可以閱讀更多內容並查看不同的示例,以了解如何訪問 Excel 文件數據.

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

在使用 Excel 試算表進行應用程式構建時,我們通常基於數據分析結果,需要將 Excel 文件中的數據在 C# 中解析成所需格式以獲得正確的結果。 在 C# 環境中使用 IronXL 可以輕鬆將數據解析成不同格式; 查看以下步驟。

using IronXL;
static void Main(string [] args)
{
    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;

    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;
static void Main(string [] args)
{
    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;

    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
Shared Sub Main(ByVal args() As String)
	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

	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
VB   C#

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

現在我們來談談如何解析Excel檔案數據。 首先,我們查看如何處理數字 Excel 資料,然後解析成我們所需的格式。

在 C# 中讀取 CSV 文件:教程,圖 8:每種數據類型的摘要表

每種資料類型的摘要表

static void Main(string [] args)
{
    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;
    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();
}
static void Main(string [] args)
{
    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;
    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();
}
Shared Sub Main(ByVal args() As String)
	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
	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
VB   C#

此代碼將顯示以下輸出:

在C#中讀取CSV檔案:教程,圖9:帶有正確數據類型的控制台輸出

具有正確資料類型的控制台輸出

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

在 C# 中讀取 CSV 文件: 教程, 圖 10: 在 Excel 中顯示正確的數據類型

在 Excel 中顯示正確的數據類型

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

bool Val = ws ["Cell Address"].BoolValue;
bool Val = ws ["Cell Address"].BoolValue;
Dim Val As Boolean = ws ("Cell Address").BoolValue
VB   C#

10. 如何將 Excel 文件解析成 C# 集合

static void Main(string [] args)
{
   WorkBook wb = WorkBook.Load("sample.xlsx");
   WorkSheet ws = wb.GetWorkSheet("Sheet1");
   var array = ws ["B6:F6"].ToArray();
   int item = array.Count();
   string total_items = array [0].Value.ToString();
   Console.WriteLine("First item in the array: {0}", item);
   Console.WriteLine("Total items from B6 to F6: {0}",total_items);
   Console.ReadKey();
}
static void Main(string [] args)
{
   WorkBook wb = WorkBook.Load("sample.xlsx");
   WorkSheet ws = wb.GetWorkSheet("Sheet1");
   var array = ws ["B6:F6"].ToArray();
   int item = array.Count();
   string total_items = array [0].Value.ToString();
   Console.WriteLine("First item in the array: {0}", item);
   Console.WriteLine("Total items from B6 to F6: {0}",total_items);
   Console.ReadKey();
}
Shared Sub Main(ByVal args() As String)
   Dim wb As WorkBook = WorkBook.Load("sample.xlsx")
   Dim ws As WorkSheet = wb.GetWorkSheet("Sheet1")
   Dim array = ws ("B6:F6").ToArray()
   Dim item As Integer = array.Count()
   Dim total_items As String = array (0).Value.ToString()
   Console.WriteLine("First item in the array: {0}", item)
   Console.WriteLine("Total items from B6 to F6: {0}",total_items)
   Console.ReadKey()
End Sub
VB   C#

10.1 如何將 Excel WorkSheet 解析為 DataTable

IronXL 的一項出色功能是我們可以輕鬆將特定的 Excel WorkSheet 轉換為 DataTable。 為此,我們可以使用`.ToDataTable()IronXL 的功能如下:

static void Main(string [] args)
{
    WorkBook wb = WorkBook.Load("sample.xlsx");
    WorkSheet ws = wb.GetWorkSheet("Sheet1");
    //parse sheet1 of sample.xlsx file into DataTable.
    //we set parameter true of ToDataTable() function,so first row of Excel file becomes columnname of DataTable
    DataTable dt = ws.ToDataTable(true);
}
static void Main(string [] args)
{
    WorkBook wb = WorkBook.Load("sample.xlsx");
    WorkSheet ws = wb.GetWorkSheet("Sheet1");
    //parse sheet1 of sample.xlsx file into DataTable.
    //we set parameter true of ToDataTable() function,so first row of Excel file becomes columnname of DataTable
    DataTable dt = ws.ToDataTable(true);
}
Shared Sub Main(ByVal args() As String)
	Dim wb As WorkBook = WorkBook.Load("sample.xlsx")
	Dim ws As WorkSheet = wb.GetWorkSheet("Sheet1")
	'parse sheet1 of sample.xlsx file into DataTable.
	'we set parameter true of ToDataTable() function,so first row of Excel file becomes columnname of DataTable
	Dim dt As DataTable = ws.ToDataTable(True)
End Sub
VB   C#

10.2 如何將 Excel 文件解析為 DataSet

如果我們想將完整的 Excel 文件解析成 DataSet,那麼為此我們可以使用`.ToDataSet()在 IronXL 中的 function。

static void Main(string [] args)
{
    WorkBook wb = WorkBook.Load("sample.xlsx");
    //parse WorkBook wb into DataSet
    DataSet ds = wb.ToDataSet();
    //we also can get DataTable from ds which is actually WorkSheet as:
    DataTable dt=ds.Tables [0];
}
static void Main(string [] args)
{
    WorkBook wb = WorkBook.Load("sample.xlsx");
    //parse WorkBook wb into DataSet
    DataSet ds = wb.ToDataSet();
    //we also can get DataTable from ds which is actually WorkSheet as:
    DataTable dt=ds.Tables [0];
}
Shared Sub Main(ByVal args() As String)
	Dim wb As WorkBook = WorkBook.Load("sample.xlsx")
	'parse WorkBook wb into DataSet
	Dim ds As DataSet = wb.ToDataSet()
	'we also can get DataTable from ds which is actually WorkSheet as:
	Dim dt As DataTable=ds.Tables (0)
End Sub
VB   C#

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

IronXL 提供了一種在特定範圍內讀取 Excel 文件數據的智能方法。 範圍可以應用於行和列。

static void Main(string [] args)
{
    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();
}
static void Main(string [] args)
{
    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();
}
Shared Sub Main(ByVal args() As String)
	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
VB   C#

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

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

控制台輸出以訪問範圍 B3:B8 的所有值

並生成 Excel 文件 sample.xlsx 的值:

在 C# 中讀取 CSV 檔案:教學,圖 12:從 sample.xlsx 顯示的數據

從 sample.xlsx 顯示數據

此外,IronXL 也兼容許多 Excel 方法,以便與儲存格進行互動,包括樣式和邊框, 數學函數, 條件 [格式]或從可用數據創建圖表。

11. 如何在 Excel 文件中讀取布林數據

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

static void Main(string [] args)
{
   WorkBook wb = WorkBook.Load("sample.xlsx");
   WorkSheet ws = wb.GetWorkSheet("Sheet1");
   foreach (var item in ws ["G1:G10"])
   {
   Console.WriteLine("  Condition is: {0}", item.BoolValue);
   }
   Console.ReadKey();
}
static void Main(string [] args)
{
   WorkBook wb = WorkBook.Load("sample.xlsx");
   WorkSheet ws = wb.GetWorkSheet("Sheet1");
   foreach (var item in ws ["G1:G10"])
   {
   Console.WriteLine("  Condition is: {0}", item.BoolValue);
   }
   Console.ReadKey();
}
Shared Sub Main(ByVal args() As String)
   Dim wb As WorkBook = WorkBook.Load("sample.xlsx")
   Dim ws As WorkSheet = wb.GetWorkSheet("Sheet1")
   For Each item In ws ("G1:G10")
   Console.WriteLine("  Condition is: {0}", item.BoolValue)
   Next item
   Console.ReadKey()
End Sub
VB   C#

從這裡,我們得到輸出:

在 C# 中讀取 CSV 檔案:教程,第13圖:從獲取布林數據的控制台輸出

從獲取布林數據的控制台輸出

以及包含從 C1 到 C10 值的 Excel 文件 sample.xlsx:

在C#中讀取CSV文件:教程,圖14:用於與控制台輸出比較的Excel樣本

用於與控制台輸出進行比較的 Excel 範例

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

使用行和列索引可以輕鬆讀取完整的Excel工作表。 為此,我們使用兩個循環:一個用於遍歷所有行,另一個用於遍歷特定行的所有列。 然後我們可以輕鬆獲取整個 Excel 工作表中的所有單元格值。

static void Main(string [] args)
{
    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();
}
static void Main(string [] args)
{
    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();
}
Shared Sub Main(ByVal args() As String)
	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
VB   C#

用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 標準

  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
VB   C#

現在在主函數內寫下以下代碼。

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);
}
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);
}
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
VB   C#

在C#中讀取CSV文件:教程,圖16:每個單元格的控制台輸出

每個單元的控制台輸出

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

14. 結論和IronXL特別優惠

除了CSV 解析在 C# 中,IronXL 只需兩行代碼即可將 CSV 文件轉換為 Excel 文件。!

使用 C# 或 VB.NET,可以非常輕鬆地使用 IronXL 的 Excel API,而無需 Interop。您可以讀取、編輯和創建 Excel 試算表或使用其他 Excel 格式,例如XLS/XLSX/CSV/TSV. 在多個框架支持下,您可以以兩個產品的價格購買五個產品。 點擊我們的價格頁面如需更多資訊。

在C# 中读取CSV文件:教程,图17:Iron Suite的5款产品

Iron Suite 的五款產品

< 上一頁
如何在 Excel 中突出顯示每隔一行
下一個 >
如何鎖定 Excel 中的儲存格:逐步教學

準備開始了嗎? 版本: 2024.11 剛剛發布

免費 NuGet 下載 總下載次數: 1,111,773 查看許可證 >