如何在 C&#35 中导入 Excel 文件;

This article was translated from English: Does it need improvement?
Translated
View the article in English

作为开发人员,我们经常需要从 Excel 文件中导入数据,并用它来满足我们的应用程序和数据管理要求。IronXL 为我们提供了一种简便的方法,无需多行代码即可将所需数据直接导入 C# 项目,然后以编程方式对其进行操作。


步骤 1

1.使用 IronXL 库导入数据

使用 IronXL Excel 库提供的功能导入数据,我们将在本教程中使用 IronXL Excel 库。该软件可免费用于开发。

安装到您的 通过 DLL 下载 C# 项目 或导航 使用 NuGet 软件包.


Install-Package IronXL.Excel

教程

2.获取项目工作表

为了满足今天的项目需求,我们将使用步骤 1 中安装的 IronXL 软件,将 Excel 数据导入 C# 应用程序。

第 2 步,我们将在 CSharp 项目中使用 `WorkBook.Load' 加载 Excel 工作簿。()函数。我们将 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")
VB   C#

将在 wb 中加载指定路径下的 Excel 文件。

接下来,我们需要访问 Excel 文件中的特定工作表,并将其数据导入到项目中。为此,我们可以使用 `GetWorkSheet()函数。我们将在该函数中传递工作表名称作为字符串参数,以指定要导入的工作簿工作表。

//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")
VB   C#

WorkSheet 将以 ws 的形式导入,而 wb 则是我们在上述示例代码中定义的 WorkBook。

还有以下其他方法可将 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()
VB   C#

现在,我们可以从指定的 Excel 文件中轻松导入任何类型的数据。让我们看看在我们的项目中导入 Excel 文件数据可能用到的所有方面。


3.在 C&num 中导入 Excel 数据;

这是在我们的项目中导入 Excel 文件数据的基本方面。

为此,我们可以使用单元格寻址系统来指定需要导入的单元格数据。它将返回 Excel 文件中特定单元格地址的值。

WorkSheet ["Cell Address"];
WorkSheet ["Cell Address"];
WorkSheet ("Cell Address")
VB   C#

我们还可以使用行和列索引从 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]
VB   C#

如果要将导入的单元格值赋值到变量中,可以使用以下代码。

/**
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()
VB   C#

在上述示例中,行和列索引从 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")
VB   C#

有关与 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
VB   C#

上述代码会显示以下输出结果:

Excel 文件 sample.xlsx 的值为


5.通过聚合函数导入 Excel 数据

我们还可以对 Excel 文件应用聚合函数,并导入这些聚合函数产生的数据。下面是一些不同函数的示例和使用方法。

  • 和()`
 //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()
VB   C#
  • 平均值()`
 //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()
VB   C#
  • 最小()`
 //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()
VB   C#
  • 最大()`
 //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()
VB   C#

您可以阅读更多关于与 Excel 中的 C# 聚合函数 并了解更多有关用不同方法提取数据的信息。

让我们看看如何应用这些函数导入 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
VB   C#

上述代码的输出结果如下

我们的文件 sample.xlsx 将包含这些值:


6.导入完整的 Excel 文件数据

如果我们想在 CSharp 项目中导入完整的 Excel 文件数据,那么我们可以先将加载的 WorkBook 解析为 DataSet。这样,完整的 Excel 数据将被导入 DataSet,Excel 文件中的工作表将成为 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()
VB   C#

这样,我们指定的工作表就会被导入到一个 DataSet 中,我们可以根据自己的需要使用它。

通常,Excel 文件的第一列被用作 ColumnName。在这种情况下,我们需要将第一列作为数据表的 ColumnName。为此,我们要设置 `ToDataSet' 的布尔参数()IronXL 的功能如下:

ToDataSet(true);
ToDataSet(true);
ToDataSet(True)
VB   C#

这将使 Excel 文件的第一列成为数据表的 ColumnName。

让我们看看如何将 Excel 数据导入数据集,并将 Excel 工作表的第一列用作数据表列名的完整示例:

/**
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
VB   C#

Excel 数据集和数据表 函数可能比较复杂,但我们有更多的示例可用于将文件数据整合到您的 C# 项目中。


图书馆快速访问

探索 IronXL 参考资料

有关通过单元格、范围、数据集和数据表提取 Excel 数据的更多信息,请参阅我们的完整文档《IronXl 的 API 参考》。

探索 IronXL 参考资料