如何在 C# 中匯入 Excel 檔案
IronXL 讓 C# 開發人員只需一行程式碼即可匯入 Excel 資料,支援 XLSX、CSV 等格式,無須依賴 Interop。匯入後即可存取儲存格、範圍及工作表以處理資料。
快速入門:立即載入 Excel 檔案只要呼叫一次 IronXL 不受逾時限制的 API,即可在幾秒內載入支援的 Excel 工作表(如 XLSX 和 CSV 格式),無須使用 Interop。載入後即可視需要存取活頁簿中的儲存格、範圍或工作表。
-
1使用 IronXL 安裝 NuGet Package Manager
-
2複製並運行這段程式碼。
WorkBook wb = IronXL.WorkBook.Load("path/to/data.xlsx");Dim wb As WorkBook = WorkBook.Load("path/to/data.xlsx")Dim wb As WorkBook = WorkBook.Load("path/to/data.xlsx") -
3部署到您的生產環境進行測試
立即在您的項目中開始使用 IronXL,並使用 免費試用
在 C# 中匯入 Excel 資料
- 使用 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 套件安裝。如需詳細安裝步驟,請參閱入門指南。
方法教學
在您的專案中存取工作表
基本活頁簿載入流程
本教學會使用步驟 1 安裝的 IronXL,將 Excel 資料匯入 C# 應用程式。此程式庫支援多種 Excel 格式,並提供簡便的試算表載入方法。
在步驟 2 中,請在 C# 專案中使用 IronXL 的WorkBook.Load()方法載入 Excel WorkBook,並將 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")' 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")' 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()' 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")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)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' 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")Dim rangeData = ws("Starting Cell Address:Ending Cell Address")完整範圍匯入範例
若要瞭解如何在 Excel 檔案中操作範圍,以及如何以不同方式擷取資料,請參考下列範例。範例示範如何匯入個別儲存格的值及整個範圍:
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();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()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()' To find the sum of a specific cell range Dim sum = ws("Starting Cell Address:Ending Cell Address").Sum() -
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()' To find the average of a specific cell range Dim average = ws("Starting Cell Address:Ending Cell Address").Avg() -
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()' To find the minimum in a specific cell range Dim minimum = ws("Starting Cell Address:Ending Cell Address").Min() -
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()' To find the maximum in a specific cell range Dim maximum = ws("Starting Cell Address:Ending Cell Address").Max()
一起使用多個彙總函數
您可以進一步瞭解如何在 C# 中使用彙總函數處理 Excel 資料,以及如何以不同方式擷取資料。這些函數特別適合用來產生摘要統計或驗證匯入的資料。
請參閱應用這些功能匯入 Excel 檔案資料的範例:
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();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()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會成為該DataSet中的DataTables。這種做法特別適合資料庫作業或使用資料繫結控制項的情況。您也可以進一步瞭解如何透過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()' 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);netnet這會將 Excel 檔案的第一列用作DataTable的欄名,以維持結構化 Excel 資料的完整性。
完整DataSet匯入範例
查看一個完整的範例,將Excel資料匯入DataSet並將Excel WorkSheet的第一列用作DataTable欄名稱:
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();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()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的指南。
ToDataSet會將所有列同時保留在記憶體中,適用於大多數匯入作業的檔案大小。如果來源檔案大到DataSet成為瓶頸,可以串流分批讀取各列,並分批寫入目的地。如此一來,記憶體用量的峰值取決於批次大小,而非總列數。
快速查閱程式庫文件
常見問題
如何使用IronXL將Excel檔案匯入C#專案?
您可以使用IronXL的WorkBook.Load()方法將Excel檔案匯入C#專案。此方法允許您載入XLSX、CSV及其他格式,無需Interop依賴。
我可以使用IronXL在C#中匯入哪些格式?
IronXL支援匯入各種試算表格式,包括XLSX、CSV、TSV等,無需Interop即可將其匯入到C#專案中。
是否可以使用C#中的IronXL存取Excel檔案中的特定工作表?
是的,您可以使用IronXL中的GetWorkSheet()方法,通過將工作表名稱作為字串參數來存取Excel檔案中的特定工作表。
IronXL能夠在C#中對匯入的Excel資料執行聚合函數嗎?
是的,IronXL允許您在從Excel檔案匯入的資料上執行如Sum()、Avg()、Min()及Max()等聚合函數。
我如何在IronXL中匯入特定範圍的Excel儲存格資料?
您可以使用範圍函數語法,例如ws["起始儲存格位址:結束儲存格位址"],以在IronXL中從指定的Excel儲存格範圍取得值。
是否可以在C#中使用IronXL將Excel資料作為DataSet使用?
是的,您可以使用IronXL的ToDataSet()方法將整個Excel檔案資料匯入DataSet。此方法對於資料庫操作或資料繫結控制項特別有用。
IronXL可以將Excel檔的第一列用作欄名嗎?
是的,當將Excel資料匯入DataSet時,您可以使用IronXL的ToDataSet(true)方法設置第一列為欄名。
如何使用IronXL從Excel儲存格匯入數值或日期值?
在IronXL中,您可以使用.DecimalValue匯入數值,並使用.DateTimeValue匯入日期值,以確保它們為正確的資料類型。
使用IronXL在C#中匯入Excel與使用Interop相比有何優勢?
IronXL無需Interop依賴,適合在無法安裝Microsoft Office的伺服器環境和雲端部署中使用。
IronXL是否可免費用於開發目的?
是的,IronXL可免費用於開發目的,提供一個全面的C# Excel API,以簡化Excel檔案處理。
Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。



