C# 读取 XLSX 文件

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

在处理各种 Excel 格式文件时,经常需要读取数据并以编程方式对其进行操作。在下面的教程中,我们将学习如何使用便捷的工具 IronXL,用 C# 从 Excel 电子表格中读取数据。


步骤 1

1.为您的项目获取 IronXL

在您的项目中使用 IronXL,以一种简单的方式在 C# 中处理 Excel 文件格式。您可以 通过直接下载安装 IronXL 或者您也可以使用 为 Visual Studio 安装 NuGet.该软件的开发是免费的。

Install-Package IronXL.Excel

教程

2.加载工作簿

WorkBook "是 IronXL 的一个类,其对象提供了对 Excel 文件及其全部功能的完全访问。例如,如果要访问 Excel 文件,我们可以使用以下代码:

/**
Load Workbook
anchor-load-workbook
**/
WorkBook wb = WorkBook.Load("sample.xlsx");//Excel file path
/**
Load Workbook
anchor-load-workbook
**/
WorkBook wb = WorkBook.Load("sample.xlsx");//Excel file path
'''
'''Load Workbook
'''anchor-load-workbook
'''*
Dim wb As WorkBook = WorkBook.Load("sample.xlsx") 'Excel file path
VB   C#

在上述代码中,WorkBook.Load()函数将sample.xlsx加载到wb中。通过访问 Excel 文件的特定工作表,可以在wb` 上执行任何类型的函数。


3.访问特定工作表

要访问 Excel 文件中的特定工作表,IronXL 提供了 WorkSheet 类。它有几种不同的使用方法:

/**
Access Sheet by Name
anchor-access-specific-worksheet
**/
WorkSheet ws = wb.GetWorkSheet("Sheet1"); //by sheet name
/**
Access Sheet by Name
anchor-access-specific-worksheet
**/
WorkSheet ws = wb.GetWorkSheet("Sheet1"); //by sheet name
'''
'''Access Sheet by Name
'''anchor-access-specific-worksheet
'''*
Dim ws As WorkSheet = wb.GetWorkSheet("Sheet1") 'by sheet name
VB   C#

wb "是在上述部分中声明的 WorkBook。

/**
Access Sheet by Index
anchor-access-specific-worksheet
**/
WorkSheet ws = wb.WorkSheets [0]; //by sheet index
/**
Access Sheet by Index
anchor-access-specific-worksheet
**/
WorkSheet ws = wb.WorkSheets [0]; //by sheet index
'''
'''Access Sheet by Index
'''anchor-access-specific-worksheet
'''*
Dim ws As WorkSheet = wb.WorkSheets (0) 'by sheet index
VB   C#

WorkSheet ws = wb.DefaultWorkSheet; //for the default sheet: 
WorkSheet ws = wb.DefaultWorkSheet; //for the default sheet: 
Dim ws As WorkSheet = wb.DefaultWorkSheet 'for the default sheet:
VB   C#

WorkSheet ws = wb.WorkSheets.First();//for the first sheet:
WorkSheet ws = wb.WorkSheets.First();//for the first sheet:
Dim ws As WorkSheet = wb.WorkSheets.First() 'for the first sheet:
VB   C#

WorkSheet ws = wb.WorkSheets.FirstOrDefault();//for the first or default sheet:
WorkSheet ws = wb.WorkSheets.FirstOrDefault();//for the first or default sheet:
Dim ws As WorkSheet = wb.WorkSheets.FirstOrDefault() 'for the first or default sheet:
VB   C#

获取 ExcelSheet ws 后,您可以从中获取任何类型的数据,并在其上执行所有 Excel 函数。


4.从工作表中获取数据

在此过程中,可以从 ExcelSheet ws 中访问数据:

string c = ws ["cell address"].ToString(); //for string
Int32 val = ws ["cell address"].Int32Value; //for integer
string c = ws ["cell address"].ToString(); //for string
Int32 val = ws ["cell address"].Int32Value; //for integer
Dim c As String = ws ("cell address").ToString() 'for string
Dim val As Int32 = ws ("cell address").Int32Value 'for integer
VB   C#

还可以从特定列的多个单元格中获取数据。

foreach (var cell in ws ["A2:A10"])
{
    Console.WriteLine("value is: {0}",  cell.Text);
}
foreach (var cell in ws ["A2:A10"])
{
    Console.WriteLine("value is: {0}",  cell.Text);
}
For Each cell In ws ("A2:A10")
	Console.WriteLine("value is: {0}", cell.Text)
Next cell
VB   C#

它将显示单元格 A2A10 的值。

此处提供了上述具体内容的完整代码示例。

/**
Access WorkSheet Data
anchor-access-data-from-worksheet
**/
using IronXL;
static void Main(string [] args)
{
    WorkBook wb = WorkBook.Load("sample.xlsx");
    WorkSheet ws = wb.GetWorkSheet("Sheet1");
    foreach (var cell in ws ["A2:A10"])
    {
        Console.WriteLine("value is: {0}", cell.Text);
    }
    Console.ReadKey();
}
/**
Access WorkSheet Data
anchor-access-data-from-worksheet
**/
using IronXL;
static void Main(string [] args)
{
    WorkBook wb = WorkBook.Load("sample.xlsx");
    WorkSheet ws = wb.GetWorkSheet("Sheet1");
    foreach (var cell in ws ["A2:A10"])
    {
        Console.WriteLine("value is: {0}", cell.Text);
    }
    Console.ReadKey();
}
'''
'''Access WorkSheet Data
'''anchor-access-data-from-worksheet
'''*
Imports IronXL
Shared Sub Main(ByVal args() As String)
	Dim wb As WorkBook = WorkBook.Load("sample.xlsx")
	Dim ws As WorkSheet = wb.GetWorkSheet("Sheet1")
	For Each cell In ws ("A2:A10")
		Console.WriteLine("value is: {0}", cell.Text)
	Next cell
	Console.ReadKey()
End Sub
VB   C#

将显示以下结果:

使用 Excel 文件 Sample.xlsx

我们可以看到,使用这些方法在项目中使用 Excel 文件数据是多么轻松。


5.对数据执行函数

通过下面的代码,可以非常简单地从 Excel 工作表中应用汇总函数(如求和、最小值或最大值)来访问过滤后的数据:

decimal sum = ws ["From:To"].Sum();
decimal min = ws ["From:To"].Min();
decimal max = ws ["From:To"].Max();
decimal sum = ws ["From:To"].Sum();
decimal min = ws ["From:To"].Min();
decimal max = ws ["From:To"].Max();
Dim sum As Decimal = ws ("From:To").Sum()
Dim min As Decimal = ws ("From:To").Min()
Dim max As Decimal = ws ("From:To").Max()
VB   C#

如果您想了解更多详情,请参阅我们的深入教程《如何 编写 C# Excel 文件 汇总功能的具体内容。

/**
Sum Min Max Functions
anchor-perform-functions-on-data
**/
using IronXL;
static void Main(string [] args)
{
    WorkBook wb = WorkBook.Load("sample.xlsx");
    WorkSheet ws = wb.GetWorkSheet("Sheet1");

    decimal sum = ws ["G2:G10"].Sum();
    decimal min = ws ["G2:G10"].Min();
    decimal max = ws ["G2:G10"].Max();

    Console.WriteLine("Sum is: {0}", sum);
    Console.WriteLine("Min is: {0}", min);
    Console.WriteLine("Max is: {0}", max);
    Console.ReadKey();
}
/**
Sum Min Max Functions
anchor-perform-functions-on-data
**/
using IronXL;
static void Main(string [] args)
{
    WorkBook wb = WorkBook.Load("sample.xlsx");
    WorkSheet ws = wb.GetWorkSheet("Sheet1");

    decimal sum = ws ["G2:G10"].Sum();
    decimal min = ws ["G2:G10"].Min();
    decimal max = ws ["G2:G10"].Max();

    Console.WriteLine("Sum is: {0}", sum);
    Console.WriteLine("Min is: {0}", min);
    Console.WriteLine("Max is: {0}", max);
    Console.ReadKey();
}
'''
'''Sum Min Max Functions
'''anchor-perform-functions-on-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 sum As Decimal = ws ("G2:G10").Sum()
	Dim min As Decimal = ws ("G2:G10").Min()
	Dim max As Decimal = ws ("G2:G10").Max()

	Console.WriteLine("Sum is: {0}", sum)
	Console.WriteLine("Min is: {0}", min)
	Console.WriteLine("Max is: {0}", max)
	Console.ReadKey()
End Sub
VB   C#

该代码将显示以下输出:

这就是 Excel 文件 Sample.xlsx 的外观:


6.将 Excel 工作表读作数据表

使用 IronXL,将 Excel 工作表作为数据表进行操作非常简单。

DataTable dt=WorkSheet.ToDataTable();
DataTable dt=WorkSheet.ToDataTable();
Dim dt As DataTable=WorkSheet.ToDataTable()
VB   C#

如果我们要使用 ExcelSheet 的第一行作为 DataTable 的列名,那么

DataTable dt=WorkSheet.ToDataTable(True);
DataTable dt=WorkSheet.ToDataTable(True);
Dim dt As DataTable=WorkSheet.ToDataTable([True])
VB   C#

因此,"ToDataTable "的布尔参数()将第一行设置为数据表的列名。默认情况下,其值为 False

/**
WorkSheet as DataTable
anchor-read-excel-worksheet-as-datatable
**/
using IronXL;
using System.Data; 
static void Main(string [] args)
{

    WorkBook wb = WorkBook.Load("sample.xlsx");
    WorkSheet ws = wb.GetWorkSheet("Sheet1");
    DataTable dt = ws.ToDataTable(true);//parse sheet1 of sample.xlsx file into datatable
    foreach (DataRow row in dt.Rows) //access rows
    {
        for (int i = 0; i < dt.Columns.Count; i++) //access columns of corresponding row
        {
            Console.Write(row [i]);
        }

    }
}
/**
WorkSheet as DataTable
anchor-read-excel-worksheet-as-datatable
**/
using IronXL;
using System.Data; 
static void Main(string [] args)
{

    WorkBook wb = WorkBook.Load("sample.xlsx");
    WorkSheet ws = wb.GetWorkSheet("Sheet1");
    DataTable dt = ws.ToDataTable(true);//parse sheet1 of sample.xlsx file into datatable
    foreach (DataRow row in dt.Rows) //access rows
    {
        for (int i = 0; i < dt.Columns.Count; i++) //access columns of corresponding row
        {
            Console.Write(row [i]);
        }

    }
}
'''
'''WorkSheet as DataTable
'''anchor-read-excel-worksheet-as-datatable
'''*
Imports IronXL
Imports System.Data
Shared Sub Main(ByVal args() As String)

	Dim wb As WorkBook = WorkBook.Load("sample.xlsx")
	Dim ws As WorkSheet = wb.GetWorkSheet("Sheet1")
	Dim dt As DataTable = ws.ToDataTable(True) 'parse sheet1 of sample.xlsx file into datatable
	For Each row As DataRow In dt.Rows 'access rows
		For i As Integer = 0 To dt.Columns.Count - 1 'access columns of corresponding row
			Console.Write(row (i))
		Next i

	Next row
End Sub
VB   C#

使用上述代码,可以根据需要访问和使用工作表的每个单元格值。


7.将 Excel 文件作为数据集读取

IronXL 为如何使用完整的 Excel 文件提供了非常简单的功能 (工作簿) 作为数据集。

DataSet ds = WorkBook.ToDataSet();
DataSet ds = WorkBook.ToDataSet();
Dim ds As DataSet = WorkBook.ToDataSet()
VB   C#

WorkBook 就是你的 Excel 文件,如下图所示:

在本示例中,我们将了解如何将 Excel 文件用作数据集。

/**
Excel File as DataSet
anchor-read-excel-file-as-dataset
**/
using IronXL;
using System.Data; 
static void Main(string [] args)
{           
    WorkBook wb = WorkBook.Load("sample.xlsx");
    DataSet ds = wb.ToDataSet(); //Parse WorkBook wb into DataSet
    foreach (DataTable dt in ds.Tables)
    {
        Console.WriteLine(dt.TableName);
    }
}
/**
Excel File as DataSet
anchor-read-excel-file-as-dataset
**/
using IronXL;
using System.Data; 
static void Main(string [] args)
{           
    WorkBook wb = WorkBook.Load("sample.xlsx");
    DataSet ds = wb.ToDataSet(); //Parse WorkBook wb into DataSet
    foreach (DataTable dt in ds.Tables)
    {
        Console.WriteLine(dt.TableName);
    }
}
'''
'''Excel File as DataSet
'''anchor-read-excel-file-as-dataset
'''*
Imports IronXL
Imports System.Data
Shared Sub Main(ByVal args() As String)
	Dim wb As WorkBook = WorkBook.Load("sample.xlsx")
	Dim ds As DataSet = wb.ToDataSet() 'Parse WorkBook wb into DataSet
	For Each dt As DataTable In ds.Tables
		Console.WriteLine(dt.TableName)
	Next dt
End Sub
VB   C#

上述代码的输出结果如下:

Excel 文件 Sample.xlsx 将显示如下:

在上述示例中,我们可以轻松地将 Excel 文件解析为 DataSet,并将 Excel 文件中的每个工作表作为 DataTable 执行。深入了解如何 将 Excel 作为 DataSet 进行解析 这里有代码示例。

让我们再看一个如何访问所有 Excel 表中每个单元格值的示例。在这里,我们可以访问 Excel 文件中每个工作表的每个单元格值。

/**
WorkSheet Cell Values
anchor-read-excel-file-as-dataset
**/
using IronXL;
using System.Data; 
static void Main(string [] args)
{ 
WorkBook wb = WorkBook.Load("sample.xlsx");
DataSet ds = wb.ToDataSet();//behave complete Excel file as DataSet
foreach (DataTable dt in ds.Tables)//behave Excel WorkSheet as DataTable. 
{
    foreach (DataRow row in dt.Rows)//corresponding Sheet's Rows
    {
        for (int i = 0; i < dt.Columns.Count; i++)//Sheet columns of corresponding row
        {
            Console.Write(row [i]);
        }
    }
}
}
/**
WorkSheet Cell Values
anchor-read-excel-file-as-dataset
**/
using IronXL;
using System.Data; 
static void Main(string [] args)
{ 
WorkBook wb = WorkBook.Load("sample.xlsx");
DataSet ds = wb.ToDataSet();//behave complete Excel file as DataSet
foreach (DataTable dt in ds.Tables)//behave Excel WorkSheet as DataTable. 
{
    foreach (DataRow row in dt.Rows)//corresponding Sheet's Rows
    {
        for (int i = 0; i < dt.Columns.Count; i++)//Sheet columns of corresponding row
        {
            Console.Write(row [i]);
        }
    }
}
}
'''
'''WorkSheet Cell Values
'''anchor-read-excel-file-as-dataset
'''*
Imports IronXL
Imports System.Data
Shared Sub Main(ByVal args() As String)
Dim wb As WorkBook = WorkBook.Load("sample.xlsx")
Dim ds As DataSet = wb.ToDataSet() 'behave complete Excel file as DataSet
For Each dt As DataTable In ds.Tables 'behave Excel WorkSheet as DataTable.
	For Each row As DataRow In dt.Rows 'corresponding Sheet's Rows
		For i As Integer = 0 To dt.Columns.Count - 1 'Sheet columns of corresponding row
			Console.Write(row (i))
		Next i
	Next row
Next dt
End Sub
VB   C#

使用上述示例,可以非常方便地访问 Excel 文件中每个工作表的每个单元格值。

有关如何 无需互操作即可读取 Excel 文件 在此查看代码。


教程快速访问

IronXL 应用程序接口参考

请在文档中阅读有关 IronXL 功能、类、方法字段、命名空间和枚举的更多信息。

IronXL 应用程序接口参考