如何在 C&#35 中匯入 Excel 檔案

This article was translated from English: Does it need improvement?
Translated
View the article in English

作為開發人員,我們經常需要從 Excel 檔案中匯入數據,並利用這些數據來滿足我們的應用程式和數據管理需求。IronXL 為我們提供了一種簡單的方法,無需編寫大量程式碼,即可將所需數據直接匯入 C# 專案中,然後進行程式化處理。


第一步

1. 使用 IronXL 庫匯入資料

使用 IronXL Excel 庫提供的函數匯入資料,我們將在本教程中使用該軟體。此軟體可供免費開發使用。

安裝到您的 C#專案透過DLL下載 或者導航 使用 NuGet 套件.


Install-Package IronXL.Excel

如何操作教程

2. 進入專案的工作表

針對我們今天的專案需求,我們將使用第一步中安裝的 IronXL 軟體,把 Excel 資料匯入到我們的 C# 應用程式中。

在第二步中,我們將使用 WorkBook.Load 在 CSharp 專案中加載我們的 Excel 工作簿()IronXL 的功能。我們在此函式中以字串參數傳遞 Excel WorkBook 的路徑,如下所示:

//load Excel file
WorkBook wb = WorkBook.Load("Path");
//load Excel file
WorkBook wb = WorkBook.Load("Path");
'load Excel file
Dim wb As WorkBook = WorkBook.Load("Path")
VB   C#

指定路徑的 Excel 文件將會載入到 wb 中。

接下來,我們需要訪問 Excel 文件中的特定工作表,其數據將會被導入到專案中。為此,我們可以使用 GetWorkSheet。()` function of IronXL。我們將在此函數中傳遞工作表名稱作為字串參數,以指定要匯入的工作簿中的工作表。

//specify sheet name of Excel WorkBook
WorkSheet ws = wb.GetWorkSheet("SheetName");
//specify sheet name of Excel WorkBook
WorkSheet ws = wb.GetWorkSheet("SheetName");
'specify sheet name of Excel WorkBook
Dim ws As WorkSheet = wb.GetWorkSheet("SheetName")
VB   C#

工作表將作為ws匯入,而wb是我們在上述代碼示例中定義的工作簿。

還有以下替代方式將Excel工作表匯入專案。

/**
Import WorkSheet 
anchor-access-worksheet-for-project
**/
//by sheet indexing
WorkBook.WorkSheets [SheetIndex];
//get default  WorkSheet
WorkBook.DefaultWorkSheet;
//get first WorkSheet
WorkBook.WorkSheets.First();
//for the first or default sheet:
WorkBook.WorkSheets.FirstOrDefault();
/**
Import WorkSheet 
anchor-access-worksheet-for-project
**/
//by sheet indexing
WorkBook.WorkSheets [SheetIndex];
//get default  WorkSheet
WorkBook.DefaultWorkSheet;
//get first WorkSheet
WorkBook.WorkSheets.First();
//for the first or default sheet:
WorkBook.WorkSheets.FirstOrDefault();
'''
'''Import WorkSheet 
'''anchor-access-worksheet-for-project
'''*
'by sheet indexing
WorkBook.WorkSheets (SheetIndex)
'get default  WorkSheet
WorkBook.DefaultWorkSheet
'get first WorkSheet
WorkBook.WorkSheets.First()
'for the first or default sheet:
WorkBook.WorkSheets.FirstOrDefault()
VB   C#

現在,我們可以輕鬆地從指定的 Excel 文件中導入任何類型的數據。讓我們來看看在我們的項目中使用 Excel 文件數據進口的所有可能方面。


3. 在 C# 中匯入 Excel 數據

這是我們專案中匯入 Excel 文件數據的基本方面。

為了這個目的,我們可以使用單元格地址系統來指定我們需要匯入的單元格數據。它將返回 Excel 文件中特定的單元格地址的值。

WorkSheet ["Cell Address"];
WorkSheet ["Cell Address"];
WorkSheet ("Cell Address")
VB   C#

我們也可以使用行列索引從 Excel 文件匯入儲存格數據。此行代碼將返回指定行和列索引的值。

WorkSheet.Rows [RowIndex].Columns [ColumnIndex]
WorkSheet.Rows [RowIndex].Columns [ColumnIndex]
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'WorkSheet.Rows [RowIndex].Columns [ColumnIndex]
VB   C#

如果我們想將匯入的儲存格值賦給變數,那麼我們可以使用此代碼。

/**
Import Data by Cell Address
anchor-import-excel-data-in-c-num
**/
//by cell addressing
string val = WorkSheet ["Cell Address"].ToString();
//by row and column indexing
string val = WorkSheet.Rows [RowIndex].Columns [ColumnIndex].Value.ToString();
/**
Import Data by Cell Address
anchor-import-excel-data-in-c-num
**/
//by cell addressing
string val = WorkSheet ["Cell Address"].ToString();
//by row and column indexing
string val = WorkSheet.Rows [RowIndex].Columns [ColumnIndex].Value.ToString();
'''
'''Import Data by Cell Address
'''anchor-import-excel-data-in-c-num
'''*
'by cell addressing
Dim val As String = WorkSheet ("Cell Address").ToString()
'by row and column indexing
Dim val As String = WorkSheet.Rows (RowIndex).Columns (ColumnIndex).Value.ToString()
VB   C#

在以上範例中,行和列的索引從0開始。


4. 匯入指定範圍的 Excel 數據

如果我們想從 Excel 工作簿中匯入特定範圍內的數據,可以使用 range 函數輕鬆完成。要定義範圍,我們需要描述起始單元格和結束單元格地址。這樣,它將返回位於指定範圍內的所有單元格值。

WorkSheet ["starting Cell Address : Ending Cell Address"];
WorkSheet ["starting Cell Address : Ending Cell Address"];
WorkSheet ("starting Cell Address : Ending Cell Address")
VB   C#

更多有關處理 Excel 檔案中的範圍 查看提供的代碼範例。

/**
Import Data by Range
anchor-import-excel-data-of-specific-range
**/
using IronXL;
static void Main(string [] args)
{
    //import Excel WorkBook
    WorkBook wb = WorkBook.Load("sample.xlsx");
    //specify WorkSheet
    WorkSheet ws = wb.GetWorkSheet("Sheet1");
    //import data of specific cell
    string val = ws ["A4"].Value.ToString();
    Console.WriteLine("Import Value of A4 Cell address: {0}",val);
    Console.WriteLine("import Values in Range From B3 To B9 :\n");
    //import data in specific range
    foreach (var item in ws ["B3:B9"])
    {
        Console.WriteLine(item.Value.ToString());
    }

    Console.ReadKey();
}
/**
Import Data by Range
anchor-import-excel-data-of-specific-range
**/
using IronXL;
static void Main(string [] args)
{
    //import Excel WorkBook
    WorkBook wb = WorkBook.Load("sample.xlsx");
    //specify WorkSheet
    WorkSheet ws = wb.GetWorkSheet("Sheet1");
    //import data of specific cell
    string val = ws ["A4"].Value.ToString();
    Console.WriteLine("Import Value of A4 Cell address: {0}",val);
    Console.WriteLine("import Values in Range From B3 To B9 :\n");
    //import data in specific range
    foreach (var item in ws ["B3:B9"])
    {
        Console.WriteLine(item.Value.ToString());
    }

    Console.ReadKey();
}
'''
'''Import Data by Range
'''anchor-import-excel-data-of-specific-range
'''*
Imports Microsoft.VisualBasic
Imports IronXL
Shared Sub Main(ByVal args() As String)
	'import Excel WorkBook
	Dim wb As WorkBook = WorkBook.Load("sample.xlsx")
	'specify WorkSheet
	Dim ws As WorkSheet = wb.GetWorkSheet("Sheet1")
	'import data of specific cell
	Dim val As String = ws ("A4").Value.ToString()
	Console.WriteLine("Import Value of A4 Cell address: {0}",val)
	Console.WriteLine("import Values in Range From B3 To B9 :" & vbLf)
	'import data in specific range
	For Each item In ws ("B3:B9")
		Console.WriteLine(item.Value.ToString())
	Next item

	Console.ReadKey()
End Sub
VB   C#

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

以 Excel 文件 sample.xlsx 的數值為:


5. 透過聚合函數導入 Excel 數據

我們還可以將聚合函數應用於 Excel 文件並導入這些聚合函數的結果數據。以下是一些不同函數的示例以及使用方法。

  • `Sum()```
 //to find the sum of specific cell range 
WorkSheet ["Starting Cell Address : Ending Cell Address"].Sum();
 //to find the sum of specific cell range 
WorkSheet ["Starting Cell Address : Ending Cell Address"].Sum();
'to find the sum of specific cell range 
WorkSheet ("Starting Cell Address : Ending Cell Address").Sum()
VB   C#
  • 平均()```
 //to find the average of specific cell range 
WorkSheet ["Starting Cell Address : Ending Cell Address"].Avg()
 //to find the average of specific cell range 
WorkSheet ["Starting Cell Address : Ending Cell Address"].Avg()
'to find the average of specific cell range 
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'WorkSheet ["Starting Cell Address : Ending Cell Address"].Avg()
VB   C#
  • `分()```
 //to find the Min In specific cell range 
WorkSheet ["Starting Cell Address : Ending Cell Address"].Min()
 //to find the Min In specific cell range 
WorkSheet ["Starting Cell Address : Ending Cell Address"].Min()
'to find the Min In specific cell range 
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'WorkSheet ["Starting Cell Address : Ending Cell Address"].Min()
VB   C#
  • 最大()```
 //to find the Max in specific cell range 
WorkSheet ["Starting Cell Address : Ending Cell Address"].Max()
 //to find the Max in specific cell range 
WorkSheet ["Starting Cell Address : Ending Cell Address"].Max()
'to find the Max in specific cell range 
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'WorkSheet ["Starting Cell Address : Ending Cell Address"].Max()
VB   C#

您可以閱讀更多有關使用 在 C# 中使用 Excel 的聚合函數 並了解更多有關以不同方法獲取數據的信息。

讓我們來看看如何通過應用這些功能來匯入 Excel 文件數據的示例。

/**
Import Data by Aggregate Function
anchor-import-excel-data-by-aggregate-functions
**/
using IronXL;
static void Main(string [] args)
{
    //Import Excel file
    WorkBook wb = WorkBook.Load("sample.xlsx");
    //Specify WorkSheet
    WorkSheet ws = wb.GetWorkSheet("Sheet1");
    //Import Excel file data by applying aggregate functions
    decimal Sum = ws ["D2:D9"].Sum();
    decimal Avg = ws ["D2:D9"].Avg();
    decimal Min = ws ["D2:D9"].Min();
    decimal Max = ws ["D2:D9"].Max();
    Console.WriteLine("Sum From D2 To D9: {0}", Sum);
    Console.WriteLine("Avg From D2 To D9: {0}", Avg);
    Console.WriteLine("Min From D2 To D9: {0}", Min);
    Console.WriteLine("Max From D2 To D9: {0}", Max);
    Console.ReadKey();
}
/**
Import Data by Aggregate Function
anchor-import-excel-data-by-aggregate-functions
**/
using IronXL;
static void Main(string [] args)
{
    //Import Excel file
    WorkBook wb = WorkBook.Load("sample.xlsx");
    //Specify WorkSheet
    WorkSheet ws = wb.GetWorkSheet("Sheet1");
    //Import Excel file data by applying aggregate functions
    decimal Sum = ws ["D2:D9"].Sum();
    decimal Avg = ws ["D2:D9"].Avg();
    decimal Min = ws ["D2:D9"].Min();
    decimal Max = ws ["D2:D9"].Max();
    Console.WriteLine("Sum From D2 To D9: {0}", Sum);
    Console.WriteLine("Avg From D2 To D9: {0}", Avg);
    Console.WriteLine("Min From D2 To D9: {0}", Min);
    Console.WriteLine("Max From D2 To D9: {0}", Max);
    Console.ReadKey();
}
'''
'''Import Data by Aggregate Function
'''anchor-import-excel-data-by-aggregate-functions
'''*
Imports IronXL
Shared Sub Main(ByVal args() As String)
	'Import Excel file
	Dim wb As WorkBook = WorkBook.Load("sample.xlsx")
	'Specify WorkSheet
	Dim ws As WorkSheet = wb.GetWorkSheet("Sheet1")
	'Import Excel file data by applying aggregate functions
	Dim Sum As Decimal = ws ("D2:D9").Sum()
	Dim Avg As Decimal = ws ("D2:D9").Avg()
	Dim Min As Decimal = ws ("D2:D9").Min()
	Dim Max As Decimal = ws ("D2:D9").Max()
	Console.WriteLine("Sum From D2 To D9: {0}", Sum)
	Console.WriteLine("Avg From D2 To D9: {0}", Avg)
	Console.WriteLine("Min From D2 To D9: {0}", Min)
	Console.WriteLine("Max From D2 To D9: {0}", Max)
	Console.ReadKey()
End Sub
VB   C#

上面的程式碼給我們以下輸出:

而我們的文件 sample.xlsx 將有這些值:


6. 導入完整的 Excel 檔案資料

如果我們想在 CSharp 項目中導入完整的 Excel 檔案資料,我們可以首先將加載的 WorkBook 解析成 DataSet。這樣一來,完整的 Excel 資料會被導入 DataSet,Excel 檔案上的工作表將變成該 DataSet 的 DataTable。下面是實際操作:

//import WorkBook into dataset
DataSet ds = WorkBook.ToDataSet();
//import WorkBook into dataset
DataSet ds = WorkBook.ToDataSet();
'import WorkBook into dataset
Dim ds As DataSet = WorkBook.ToDataSet()
VB   C#

這樣,我們指定的工作表將被匯入到可以根據我們需求使用的 DataSet 中。

通常,Excel 文件的第一列用作 ColumnName。在這種情況下,我們需要將第一列設為 DataTable 的 ColumnName。為此,我們需要設置 ToDataSet 的布林參數。()IronXL 的功能如下:

ToDataSet(true);
ToDataSet(true);
ToDataSet(True)
VB   C#

這將使 Excel 文件的第一列成為 DataTable 的 ColumnName。

讓我們看看如何將 Excel 數據導入 Dataset 的完整示例,並使用 Excel 工作表的第一列作為 DataTable 的 ColumnName:

/**
Import to Dataset
anchor-import-complete-excel-file-data
**/
using IronXL;
static void Main(string [] args)
{
    WorkBook wb = WorkBook.Load("sample.xlsx");
    WorkSheet ws = wb.GetWorkSheet("Sheet1");
    DataSet ds = new DataSet();
    ds = wb.ToDataSet(true);
    Console.WriteLine("Excel file data imported to dataset successfully.");
    Console.ReadKey();
}
/**
Import to Dataset
anchor-import-complete-excel-file-data
**/
using IronXL;
static void Main(string [] args)
{
    WorkBook wb = WorkBook.Load("sample.xlsx");
    WorkSheet ws = wb.GetWorkSheet("Sheet1");
    DataSet ds = new DataSet();
    ds = wb.ToDataSet(true);
    Console.WriteLine("Excel file data imported to dataset successfully.");
    Console.ReadKey();
}
'''
'''Import to Dataset
'''anchor-import-complete-excel-file-data
'''*
Imports IronXL
Shared Sub Main(ByVal args() As String)
	Dim wb As WorkBook = WorkBook.Load("sample.xlsx")
	Dim ws As WorkSheet = wb.GetWorkSheet("Sheet1")
	Dim ds As New DataSet()
	ds = wb.ToDataSet(True)
	Console.WriteLine("Excel file data imported to dataset successfully.")
	Console.ReadKey()
End Sub
VB   C#

與...合作 Excel 資料集和資料表 函數可能很複雜,但是我們有更多示例可用於將檔案數據整合到您的 C# 項目中。


資料庫快速訪問

探索 IronXL 參考資料

了解更多有關通過儲存格、範圍、數據集和數據表提取 Excel 數據的資訊,請參閱 IronXL 的完整文件 API 參考資料。

探索 IronXL 參考資料