如何在 C# 中匯入 Excel 檔案
IronXL 讓 C# 開發人員僅需一行程式碼即可匯入 Excel 資料,支援 XLSX、CSV 及其他格式,且無需依賴 Interop,可立即存取儲存格、範圍及工作表以進行資料處理。
快速入門:立即載入您的 Excel 檔案
只需透過 IronXL 的無超時 API 呼叫一次方法,您就能在數秒內載入任何受支援的 Excel 試算表(XLSX、CSV 等)——無需 Interop,輕鬆無煩惱。 請立即開始操作工作簿,視需要存取儲存格、範圍或工作表。
匯入 Excel 資料 C#
- 使用 IronXL程式庫匯入資料
- 在 C# 中匯入 Excel 資料
- 匯入特定儲存格範圍的資料
- 使用 SUM、AVG、MIN、MAX 等聚合函數匯入 Excel 資料
簡化工作流程(5 個步驟)
- 下載並安裝 C# 函式庫以匯入 Excel 檔案
- 準備待匯入的 Excel 檔案
- 使用
Load方法匯入試算表 - 使用直觀的 API 編輯已載入的 Excel 檔案
- 將編輯後的 Excel 檔案匯出為各種格式
步驟 1
安裝 IronXL程式庫
IronXL 讓 Excel 匯入更輕鬆
請使用本教學中將要使用的 IronXl.Excel 程式庫所提供的功能來匯入資料。 此軟體可供開發用途免費使用。 IronXL 提供一套完整的 C# Excel API,可簡化 Excel 檔案的操作流程,且無需依賴 Microsoft Office 或 Interop。 這使其非常適合用於伺服器環境和雲端部署。
安裝方法
透過 DLL 下載安裝至您的 C# 專案,或使用 NuGet 套件進行安裝。 如需詳細的安裝指引,請參閱我們的入門指南。
Install-Package IronXL.Excel
操作教學
在您的專案中存取工作表
工作簿的基本載入流程
針對今日的專案需求,我們將使用步驟 1 中安裝的 IronXL 軟體,將 Excel 資料匯入 C# 應用程式。此程式庫支援多種 Excel 格式,並提供直覺的方法來載入試算表。
在步驟 2 中,我們將透過 IronXL 的 WorkBook.Load() 函式,將 Excel WorkBook 檔案載入至 C# 專案中。 我們將 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")
位於指定路徑的 Excel 檔案將被載入至 wb。 此方法支援 XLSX、XLS、CSV、TSV 及其他常見的試算表格式。
存取特定工作表
接下來,我們需要存取 Excel 檔案中一個特定的 WorkSheet,其資料將被匯入至專案中。 為此,我們可使用 IronXL 的 GetWorkSheet() 函式,並將工作表名稱作為字串參數傳入,以指定要匯入 WorkBook 中的哪個工作表。 請參閱我們的完整指南,進一步了解工作表的管理方法。
// 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")
WorkSheet 將被導入為 ws,而 wb 即是我們在上述程式碼範例中定義的 WorkBook。
存取工作表的替代方法
以下是將 Excel WorkSheet 匯入專案的其他方法。 每種方法皆能根據您的具體使用情境提供靈活性:
// Import WorkSheet by various methods
// by sheet indexing
WorkSheet mySheet = wb.WorkSheets[SheetIndex];
// get default WorkSheet
WorkSheet defaultSheet = wb.DefaultWorkSheet;
// get first WorkSheet
WorkSheet firstSheet = wb.WorkSheets.First();
// for the first or default sheet
WorkSheet firstOrDefaultSheet = wb.WorkSheets.FirstOrDefault();
// Import WorkSheet by various methods
// by sheet indexing
WorkSheet mySheet = wb.WorkSheets[SheetIndex];
// get default WorkSheet
WorkSheet defaultSheet = wb.DefaultWorkSheet;
// get first WorkSheet
WorkSheet firstSheet = wb.WorkSheets.First();
// for the first or default sheet
WorkSheet firstOrDefaultSheet = wb.WorkSheets.FirstOrDefault();
' Import WorkSheet by various methods
' by sheet indexing
Dim mySheet As WorkSheet = wb.WorkSheets(SheetIndex)
' get default WorkSheet
Dim defaultSheet As WorkSheet = wb.DefaultWorkSheet
' get first WorkSheet
Dim firstSheet As WorkSheet = wb.WorkSheets.First()
' for the first or default sheet
Dim firstOrDefaultSheet As WorkSheet = wb.WorkSheets.FirstOrDefault()
現在,我們可以輕鬆地從指定的 Excel 檔案中匯入任何類型的資料。 讓我們深入探討在專案中匯入 Excel 檔案資料的所有可能方式。
在 C# 中匯入 Excel 資料
基本儲存格匯入方法
這是將 Excel 檔案資料匯入專案的基本步驟。 IronXL 提供多種存取儲存格資料的方式,使其能靈活應對各種情境。
為此,我們可以使用儲存格位址系統來指定需要匯入的儲存格資料。 它會從 Excel 檔案中擷取特定儲存格位址的值:
var cellValue = ws["Cell Address"];
var cellValue = ws["Cell Address"];
Dim cellValue = ws("Cell Address")
使用行與列索引匯入資料
我們也可以透過使用列和欄索引,從 Excel 檔案匯入儲存格資料。 這行程式碼會傳回指定列與列索引的值。 此方法在透過程式碼迭代處理資料時特別有用:
var cellValueByIndex = ws.Rows[RowIndex].Columns[ColumnIndex];
var cellValueByIndex = ws.Rows[RowIndex].Columns[ColumnIndex];
Dim cellValueByIndex = ws.Rows(RowIndex).Columns(ColumnIndex)
將匯入的值儲存至變數中
若要將匯入的儲存格值賦予變數,請使用此程式碼。 ToString() 方法可確保與字串變數的相容性,但您也可視需要將其轉換為其他類型:
// Import Data by Cell Address
// by cell addressing
string val = ws["Cell Address"].ToString();
// by row and column indexing
string valWithIndexing = ws.Rows[RowIndex].Columns[ColumnIndex].Value.ToString();
// for numeric values
decimal numericValue = ws["B2"].DecimalValue;
// for date values
DateTime dateValue = ws["C2"].DateTimeValue;
// Import Data by Cell Address
// by cell addressing
string val = ws["Cell Address"].ToString();
// by row and column indexing
string valWithIndexing = ws.Rows[RowIndex].Columns[ColumnIndex].Value.ToString();
// for numeric values
decimal numericValue = ws["B2"].DecimalValue;
// for date values
DateTime dateValue = ws["C2"].DateTimeValue;
' Import Data by Cell Address
' by cell addressing
Dim val As String = ws("Cell Address").ToString()
' by row and column indexing
Dim valWithIndexing As String = ws.Rows(RowIndex).Columns(ColumnIndex).Value.ToString()
' for numeric values
Dim numericValue As Decimal = ws("B2").DecimalValue
' for date values
Dim dateValue As DateTime = ws("C2").DateTimeValue
在上述範例中,列與行的索引從 0 開始。若需進行更進階的儲存格操作,請參閱我們關於清除儲存格與複製儲存格的指南。
從特定範圍匯入資料
範圍函式語法
若要從 Excel WorkBook 匯入特定範圍的資料,請使用 range 函式。 請透過描述起始與結束儲存格位址來定義範圍。 此操作會返回指定範圍內的所有儲存格值。 如需全面的範圍選取技巧,請參閱我們的範圍選取指南。
var rangeData = ws["Starting Cell Address:Ending Cell Address"];
var rangeData = ws["Starting Cell Address:Ending Cell Address"];
Dim rangeData = ws("Starting Cell Address:Ending Cell Address")
完整範例導入
如需進一步了解如何在 Excel 檔案中處理範圍,以及探索各種資料擷取方法,請參閱相關說明。 以下範例示範如何匯入單一儲存格值及儲存格範圍:
:path=/static-assets/excel/content-code-examples/how-to/csharp-import-excel-import.cs
using IronXL;
using System;
// 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();
Imports IronXL
Imports System
' 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 :" & vbCrLf)
' Import data in specific range
For Each item In ws("B3:B9")
Console.WriteLine(item.Value.ToString())
Next
Console.ReadKey()
上述程式碼會顯示以下輸出:
當 Excel 檔案 sample.xlsx 的值為:
使用聚合函數匯入 Excel 資料
可用的聚合函數
對 Excel 檔案套用彙總函數,並匯入這些函數產生的結果資料。 IronXL 提供內建的數學函數,讓資料分析變得簡單直觀。 以下是各項功能及其使用方式的範例:
-
Sum()// To find the sum of a specific cell range var sum = ws["Starting Cell Address:Ending Cell Address"].Sum();// To find the sum of a specific cell range var sum = ws["Starting Cell Address:Ending Cell Address"].Sum();' To find the sum of a specific cell range Dim sum = ws("Starting Cell Address:Ending Cell Address").Sum()$vbLabelText $csharpLabel -
Average()// To find the average of a specific cell range var average = ws["Starting Cell Address:Ending Cell Address"].Avg();// To find the average of a specific cell range var average = ws["Starting Cell Address:Ending Cell Address"].Avg();' To find the average of a specific cell range Dim average = ws("Starting Cell Address:Ending Cell Address").Avg()$vbLabelText $csharpLabel -
Min()// To find the minimum in a specific cell range var minimum = ws["Starting Cell Address:Ending Cell Address"].Min();// To find the minimum in a specific cell range var minimum = ws["Starting Cell Address:Ending Cell Address"].Min();' To find the minimum in a specific cell range Dim minimum = ws("Starting Cell Address:Ending Cell Address").Min()$vbLabelText $csharpLabel -
Max()// To find the maximum in a specific cell range var maximum = ws["Starting Cell Address:Ending Cell Address"].Max();// To find the maximum in a specific cell range var maximum = ws["Starting Cell Address:Ending Cell Address"].Max();' To find the maximum in a specific cell range Dim maximum = ws("Starting Cell Address:Ending Cell Address").Max()$vbLabelText $csharpLabel
同時使用多個聚合函數
進一步了解如何在 C# 中使用 Excel 的聚合函數,並探索各種資料擷取方法。 這些功能對於生成摘要統計資料或驗證匯入的資料特別有用。
請參閱以下範例,了解如何運用這些函式匯入 Excel 檔案資料:
:path=/static-assets/excel/content-code-examples/how-to/csharp-import-excel-math-functions.cs
using IronXL;
using System;
// 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();
Imports IronXL
Imports System
' 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()
上述程式碼會產生以下輸出:
而我們的檔案 sample.xlsx 包含以下值:
匯入完整的 Excel 檔案資料
ToDataSet 方法
若要將完整的 Excel 檔案資料匯入 C# 專案,請先將載入的 WorkBook 解析為 DataSet。 如此一來,Excel 檔案中完整的資料匯入至 DataSet 及 WorkSheets 之處,便會在該 DataTables 內轉為 DataSet。 此方法對於資料庫操作或處理資料綁定控制項時特別有用。 進一步了解如何以 DataSet 格式進行匯入與匯出。
// Import WorkBook into DataSet
DataSet ds = wb.ToDataSet();
// Import WorkBook into DataSet
DataSet ds = wb.ToDataSet();
' Import WorkBook into DataSet
Dim ds As DataSet = wb.ToDataSet()
這會將我們指定的 WorkSheet 匯入至 DataSet 中,以便根據需求進行使用。 此方法在同時處理多個工作表,或將 Excel 資料與 ADO.NET 操作整合時,尤其強大。
欄位標題的處理
通常,Excel 檔案的第一行會用作欄位名稱。 在此情況下,請將第一行 DataTable 設為欄位名稱。 請將 IronXL 的 ToDataSet() 函式的布林參數設定如下:
// Import WorkBook into DataSet with first row as ColumnNames
DataSet ds = wb.ToDataSet(true);
// Import WorkBook into DataSet with first row as ColumnNames
DataSet ds = wb.ToDataSet(true);
' Import WorkBook into DataSet with first row as ColumnNames
Dim ds As DataSet = wb.ToDataSet(True)
這使得 Excel 檔案 DataTable 欄位的第一行成為欄位名稱,對於處理結構化 Excel 資料時維持資料結構的完整性至關重要。
完整的 DataSet 匯入範例
請參閱將 Excel 資料匯入 DataSet 並將 Excel WorkSheet 的第一列用作 DataTable 欄位名稱的完整範例:
:path=/static-assets/excel/content-code-examples/how-to/csharp-import-excel-dataset.cs
using IronXL;
using System;
using System.Data;
WorkBook wb = WorkBook.Load("sample.xlsx");
WorkSheet ws = wb.GetWorkSheet("Sheet1");
// Import Excel data into a DataSet
DataSet ds = wb.ToDataSet(true);
Console.WriteLine("Excel file data imported to dataset successfully.");
Console.ReadKey();
Imports IronXL
Imports System
Imports System.Data
Dim wb As WorkBook = WorkBook.Load("sample.xlsx")
Dim ws As WorkSheet = wb.GetWorkSheet("Sheet1")
' Import Excel data into a DataSet
Dim ds As DataSet = wb.ToDataSet(True)
Console.WriteLine("Excel file data imported to dataset successfully.")
Console.ReadKey()
使用 Excel 的 Dataset 和 DataTable 函式可能較為複雜,但我們提供更多範例,協助您將檔案資料整合至 C# 專案中。 針對進階情境,建議參考我們關於透過 DataTable 將 Excel 匯出至 SQL 以及從 SQL 資料庫載入 Excel 的指南。
函式庫快速存取
常見問題
如何在不使用 Microsoft Office 的情況下,於 C# 中匯入 Excel 檔案?
您可以使用 IronXL 在 C# 中匯入 Excel 檔案,此過程無需 Microsoft Office 或 Interop 依賴項。只需使用 WorkBook.Load() 方法並傳入檔案路徑,例如:WorkBook wb = WorkBook.Load("path/to/data.xlsx")。此方法適用於 XLSX、XLS、CSV、TSV 及其他格式。
我可以使用這個 C# 函式庫匯入哪些 Excel 檔案格式?
IronXL 支援匯入多種 Excel 格式,包括 XLSX、XLS、CSV、TSV 及其他常見的試算表格式。同一個 WorkBook.Load() 方法會自動處理所有這些格式。
是否可以在伺服器或雲端環境中匯入 Excel 資料?
是的,IronXL 非常適合伺服器環境和雲端部署,因為它不需要 Microsoft Office 或 Interop 的依賴項。這使其成為網頁應用程式、Azure 函式以及其他伺服器端情境的理想選擇。
匯入 Excel 資料後,我多久能開始使用?
透過 IronXL 的無超時 API,您只需一行程式碼,即可在數秒內載入任何受支援的 Excel 工作表。使用 WorkBook.Load() 後,您可立即開始操作儲存格、範圍或工作表。
我可以從 Excel 檔案匯入特定的儲存格範圍嗎?
是的,IronXL 允許您在載入工作簿後,從特定的儲存格範圍匯入資料。您可以透過提供的直覺式 API,存取個別儲存格、範圍或整個工作表。
如何安裝 C# 的 Excel 匯入函式庫?
您可以透過 NuGet 套件管理員安裝 IronXL,或直接下載 DLL 檔案。此程式庫供開發用途免費使用,並提供詳盡的入門文件。





