如何在 C# 中导入 Excel 文件
IronXL 使 C# 开发人员只需一行代码即可导入 Excel 数据,支持 XLSX、CSV 和其他格式,无需 Interop 依赖性,允许立即访问单元格、范围和工作表进行数据操作。
快速入门:立即加载 Excel 文件调用一次 IronXL 的无超时限制 API,即可在几秒内加载 XLSX、CSV 等受支持的 Excel 文件,无需 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中,Excel文件中的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 数据时保持数据结构的完整性。
完整的数据集导入示例
查看将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在C#项目中导入Excel文件?
您可以通过IronXL的WorkBook.Load()方法在C#项目中导入Excel文件。此方法允许您加载XLSX、CSV和其他格式,而无需Interop依赖。
在C#中使用IronXL可以导入哪些格式?
IronXL支持将各种电子表格格式(包括XLSX、CSV、TSV等)导入您的C#项目,而无需使用Interop。
使用IronXL在C#中可以从Excel文件访问特定工作表吗?
可以,您可以在IronXL中使用GetWorkSheet()方法,通过传递工作表名称作为字符串参数来访问Excel文件中的特定工作表。
IronXL可以在C#中对导入的Excel数据执行聚合函数吗?
可以,IronXL允许您在C#项目中对从Excel文件导入的数据执行Sum()、Avg()、Min()和Max()等聚合函数。
如何在IronXL中从特定范围的Excel单元格导入数据?
您可以使用范围函数语法,如ws["Starting Cell Address:Ending Cell Address"],从IronXL中检索指定Excel单元格范围的值。
是否可以在C#中使用IronXL将Excel数据用作DataSet?
可以,您可以使用IronXL的ToDataSet()方法将完整的Excel文件数据导入到DataSet中。此方法对于数据库操作或数据绑定控件特别有用。
Excel文件的第一行可以在IronXL中用作列名吗?
可以,在将Excel数据导入到DataSet时,您可以使用IronXL的ToDataSet(true)方法将第一行设置为列名。
如何使用IronXL从Excel单元格导入数字或日期值?
在IronXL中,您可以通过使用.DecimalValue导入数字值以及.DateTimeValue导入日期值,以确保它们属于正确的数据类型。
与Interop相比,在C#中使用IronXL进行Excel导入有什么优势?
IronXL不需要Interop依赖,使其非常适合于服务器环境和不适合安装Microsoft Office的云部署。
IronXL可免费用于开发目的吗?
可以,IronXL可免费用于开发目的,提供全面的C# Excel API来简化与Excel文件的工作。
Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。



