如何在C#中導入Excel文件
作為開發人員,我們經常需要從 Excel 檔案中導入數據,並使用它來滿足我們的應用程序和數據管理需求。 IronXL讓我們可以直接在C#項目中輕鬆導入所需的數據,而且無需編寫許多代碼,然後可以以程式化的方式進行操作。
如何在 C# 中導入 Excel 文件
- 下載並安裝C#庫來匯入Excel文件
- 準備要匯入的Excel文件
- 使用
加載
導入電子表格的方法 - 使用直觀的 API 編輯載入的 Excel 文件
- 將編輯後的Excel檔案匯出成各種格式
第一步
1. 使用 IronXL 庫導入數據
使用 IronXL Excel 函式庫提供的功能導入數據,我們將在本教學中使用這個函式庫。 該軟體可免費用於開發。
將其安裝到您的C#專案透過DLL下載或者導航使用 NuGet 套件.
Install-Package IronXL.Excel
如何操作教程
2. 存取工作表以進行專案
為了我們今天的項目需求,我們將使用在第一步驟中安裝的IronXL軟體,將Excel數據導入我們的C#應用程序。
在第二步中,我們將通過使用 WorkBook.Load
在我們的 CSharp 項目中加載我們的 Excel 工作簿。()IronXL 的功能 我們將 Excel 工作簿的路徑作為字符串參數傳遞給這個函數,如下所示:
//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")
指定路徑的 Excel 檔案將會載入到 wb
。
接下來,我們需要訪問 Excel 文件中將要導入項目的特定工作表。 為了這個目的,我們可以使用 GetWorkSheet
()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")
工作表將作為 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()
現在,我們可以輕鬆從指定的Excel文件中導入任何類型的數據。 讓我們看看在我們的項目中導入Excel文件數據時可以使用的所有可能方面。
3. 在 C# 中導入 Excel 數據
這是在我們的項目中導入Excel文件數據的基本方面。
為了這個目的,我們可以使用單元格地址系統來指定我們需要導入哪些單元格數據。 它將返回 Excel 文件中特定單元格地址的值。
WorkSheet ["Cell Address"];
WorkSheet ["Cell Address"];
WorkSheet ("Cell Address")
我們也可以使用行和列索引從 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]
如果我們想將匯入的儲存格值賦給變數,那麼我們可以使用此代碼。
/**
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()
在以上範例中,行和列的索引從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")
更多有關處理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
上述程式碼顯示以下輸出:
以 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()
- 平均()```
//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()
- `分()```
//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()
- 最大()```
//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()
您可以閱讀更多有關使用在 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
上面的程式碼給我們以下輸出:
而我們的文件 sample.xlsx
將有這些值:
6. 匯入完整的 Excel 檔案資料
如果我們想要在我們的CSharp項目中導入完整的Excel文件數據,那麼我們可以先將加載的工作簿解析成一個DataSet。 透過這種方式,完整的Excel數據將被導入到DataSet中,而Excel文件上的WorkSheets將變成該DataSet的DataTables。 這是它在運行中的情形:
//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()
這樣,我們指定的工作表將被導入到一個我們可以根據我們的需求使用的 DataSet 中。
Excel 檔案的第一列通常用作列名稱。 在這個案例中,我們需要將第一列設為 DataTable 的 ColumnName。 要做到这一点,我们设置布尔参数 ToDataSet
()IronXL 的功能如下:
ToDataSet(true);
ToDataSet(true);
ToDataSet(True)
這將使 Excel 文件的第一列成為 DataTable 的 ColumnName。
讓我們來看一個完整的示例,說明如何將 Excel 數據導入到 Dataset 中,並使用 Excel WorkSheets 的第一列作為 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
與...合作Excel 資料集和資料表函數可能很複雜,但是我們有更多示例可用於將檔案數據整合到您的 C# 項目中。