如何在 C# 中导入 Excel 文件
IronXL 使 C# 开发人员只需一行代码即可导入 Excel 数据,支持 XLSX、CSV 和其他格式,无需 Interop 依赖性,允许立即访问单元格、范围和工作表进行数据操作。
快速入门:即时加载您的Excel文件只需使用 IronXL.Excel 的无超时 API 调用一个方法,您就可以在几秒钟内加载任何受支持的 Excel 表单(XLSX、CSV 等)--无需 Interop,无需大惊小怪。 立即开始与工作簿进行交互,根据需要访问单元格、区域或工作表。
-
1Install IronXL with 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
导入 Excel 数据 C#
- 使用 IronXL 库导入数据
- 在 C# 中导入 Excel 数据
- 导入特定单元格区域的数据
- 导入包含聚合函数(例如 SUM、AVG、MIN、MAX 等)的 Excel 数据
最小工作流程(5 个步骤)
- 下载并安装用于导入 Excel 文件的 C# 库
- 准备要导入的Excel文件
- 使用
Load方法导入电子表格 - 使用直观的API编辑已加载的Excel文件
- 以各种类型导出已编辑的Excel文件
步骤1
安装 IronXL 库
IronXL.Excel 让 Excel 导入更轻松
本教程将使用 IronXL Excel 库提供的函数导入数据。 该软件可免费用于开发。 IronXL.Excel 提供了全面的 C# Excel API,可简化 Excel 文件的处理,而无需 Microsoft Office 或 Interop 依赖性。 这使其成为服务器环境和云部署的理想选择。
安装方法
通过 DLL 下载或使用 NuGet 包导航将其安装到您的C# 项目中。 有关详细的安装指导,请查看我们的入门概述。
如何使用教程
在项目中获取工作表
基本工作簿加载流程
针对我们今天的项目需求,我们将使用步骤 1 中安装的 IronXL.Excel 软件将 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()上述代码显示以下输出:
With the 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()
同时使用多个聚合函数
阅读更多有关在 Excel for C# 中使用聚合函数的内容,了解更多有关以不同方法拉取数据的内容。 这些功能对于生成汇总统计数据或验证导入数据特别有用。
请参阅应用这些函数导入 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()using Excel Dataset 和 DataTable 功能可能很复杂,但我们提供更多例子来帮助您将文件数据集成到您的 C# 项目中。 对于复杂场景,可考虑探索我们关于通过 DataTable 从 Excel 到 SQL 以及从 SQL 数据库加载 Excel 的指南。
库快速访问
查阅 IronXL 参考资料
IronXL.Excel有关通过单元格、范围、数据集和数据表提取 Excel 数据的更多信息,请参阅我们的 IronXL.Excel API Reference 完整文档。
查阅 IronXL 参考资料常见问题解答
如何在不使用 Microsoft Office 的情况下用 C# 导入 Excel 文件?
您可以使用 IronXL.Excel 在 C# 中导入 Excel 文件,它不需要 Microsoft Office 或 Interop 依赖性。只需使用带有文件路径的 WorkBook.Load() 方法,例如WorkBook wb = WorkBook.Load("path/to/data.xlsx").该方法适用于 XLSX、XLS、CSV、TSV 和其他格式。
使用此 C# 库可以导入哪些 Excel 文件格式?
IronXL.Excel 支持导入各种 Excel 格式,包括 XLSX、XLS、CSV、TSV 和其他常见的电子表格格式。相同的 WorkBook.Load() 方法可自动处理所有这些格式。
是否可以在服务器或云环境中导入 Excel 数据?
是的,IronXL 是服务器环境和云部署的理想选择,因为它不需要 Microsoft Office 或 Interop 依赖性。这使得它非常适合网络应用程序、Azure Functions和其他服务器端应用场景。
导入 Excel 数据后如何快速开始工作?
利用 IronXL.Excel 的无超时 API,您只需一行代码就能在数秒内加载任何受支持的 Excel 表单。使用 WorkBook.Load() 后,您可以立即开始与单元格、范围或工作表进行交互。
能否从 Excel 文件导入特定的单元格区域?
是的,IronXL 允许您在加载工作簿后从特定单元格范围导入数据。您可以使用所提供的直观 API 访问单个单元格、单元格范围或整个工作表。
如何安装 C# 的 Excel 导入库?
您可以通过 NuGet 包管理器或直接下载 DLL 来安装 IronXL。该库可免费用于开发,并提供全面的入门文档。
Can the first row of an Excel file be used as column names in IronXL?
Yes, when importing Excel data into a DataSet, you can set the first row as column names by using the ToDataSet(true) method in IronXL.
How do I import numeric or date values from Excel cells using IronXL?
In IronXL, you can import numeric values using .DecimalValue and date values using .DateTimeValue from specific Excel cells to ensure they are in the correct data type.
What is the advantage of using IronXL for Excel import in C# over Interop?
IronXL requires no Interop dependencies, making it ideal for server environments and cloud deployments where Microsoft Office installation is not feasible.
Is IronXL available for free for development purposes?
Yes, IronXL is available for free for development purposes, providing a comprehensive C# Excel API to simplify working with Excel files.
Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。



