C#读取XLSX文件
在处理各种Excel格式时,通常需要读取数据并以编程方式操作它。 在以下教程中,我们将学习如何使用一个方便的工具 IronXL 在 C# 中从 Excel 表格读取数据。
用 C# 阅读 .XLSX 文件
步骤 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
在上述代码中,WorkBook.Load()
函数在wb
中加载sample.xlsx
。 可以通过访问 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
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
或
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:
或
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:
或
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:
获取 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
还可以从特定列的多个单元格中获取数据。
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
它将显示从单元格A2
到A10
的值。
这里提供了上述具体内容的完整代码示例。
/**
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
将显示以下结果:
使用 Excel 文件 Sample.xlsx
:
我们可以看到,使用这些方法在项目中使用 Excel 文件数据是多么轻松。
5. 对数据执行功能
通过以下代码应用聚合函数(如Sum、Min或Max),可以非常简单地访问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()
如果您想了解更多详情,请参阅我们的深入教程《如何编写 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
该代码将显示以下输出:
这就是 Excel 文件 Sample.xlsx
的外观:
6. 将 Excel 工作表读取为 DataTable
使用IronXL,将Excel工作表作为数据表操作非常简单。
DataTable dt=WorkSheet.ToDataTable();
DataTable dt=WorkSheet.ToDataTable();
Dim dt As DataTable=WorkSheet.ToDataTable()
如果我们要使用 ExcelSheet 的第一行作为 DataTable 的列名,那么
DataTable dt=WorkSheet.ToDataTable(True);
DataTable dt=WorkSheet.ToDataTable(True);
Dim dt As DataTable=WorkSheet.ToDataTable([True])
因此,"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
使用上述代码,可以根据需要访问和使用工作表的每个单元格值。
7. 将 Excel 文件读取为 DataSet
IronXL 提供了如何使用完整 Excel 文件的非常简单的功能。(工作簿)作为数据集。
DataSet ds = WorkBook.ToDataSet();
DataSet ds = WorkBook.ToDataSet();
Dim ds As DataSet = WorkBook.ToDataSet()
WorkBook 是您的 Excel 文件,正如我们下面的示例所示:
在此示例中,我们将看到如何将 Excel 文件用作 DataSet。
/**
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
上述代码的输出结果如下:
Excel 文件 Sample.xlsx
将显示如下:
在上面的示例中,我们可以看到,我们可以轻松地将 Excel 文件解析为 DataSet,并将每个 Excel 文件的 WorkSheet 作为一个 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
在上面的示例中,访问Excel文件的每个工作表的每个单元格值非常方便。
有关如何的更多信息无需互操作即可读取 Excel 文件在此查看代码。