C# 解析 Excel 文件

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

在使用 Excel 电子表格构建应用程序时,我们经常会根据数据分析结果,因此需要在 C# 中将 Excel 文件数据解析为所需格式,以获得正确的结果。在 C Sharp 环境中,使用 IronXL 和下面的步骤可以轻松地将数据解析为不同的格式。


如何用 C&num 解析 Excel 文件;

1.安装 Excel 库以处理 Excel 文件。

2.打开 "工作簿 "对象,添加 Excel 文件。

3.选择默认的 "工作表"。

4.从 Excel "工作簿 "中读取数值。

5.准确处理并显示数值。

步骤 1

1.下载 IronXL for Visual Studio

第一步是 下载 IronXL for Visual Studio 或使用 NuGet这两种免费方法都适用于开发项目。

Install-Package IronXL.Excel

教程

2.加载 Excel 文件

接下来,您需要使用 "WorkBook.Load "将 Excel 文件加载到 C# 项目中。()函数。我们通过一个字符串参数来指定 Excel 文件的路径,如下所示:

//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#

Excel 文件将以 wb 加载。现在我们可以打开一个特定的工作表。


3.打开 Excel 工作表

要打开 Excel 文件的工作表,我们使用 `WorkBook.GetWorkSheet()函数。它需要一个字符串参数来指定要打开的工作表名称。我们可以这样使用它

//specify WorkSheet
WorkSheet ws = Wb.GetWorkSheet("SheetName");
//specify WorkSheet
WorkSheet ws = Wb.GetWorkSheet("SheetName");
'specify WorkSheet
Dim ws As WorkSheet = Wb.GetWorkSheet("SheetName")
VB   C#

wb` 是我们在步骤 1 中定义的工作簿。


4.从 Excel 文件获取数据

现在,我们可以通过多种方式从打开的 Excel 工作表中轻松获取任何类型的数据。在下面的示例中,我们将看到如何访问特定单元格值并将其解析为字符串:

//Access the Data by Cell Addressing
string val = ws ["Cell Address"].ToString();
//Access the Data by Cell Addressing
string val = ws ["Cell Address"].ToString();
'Access the Data by Cell Addressing
Dim val As String = ws ("Cell Address").ToString()
VB   C#

上面一行中的 ws 是在步骤 2 中定义的工作表。这是一种简单的方法,但您可以阅读更多内容并查看不同的示例,了解如何 访问 Excel 文件数据。


5.将 Excel 数据解析为数值

现在我们来看看如何解析 Excel 文件数据。

首先,我们看看如何处理数字类型的 Excel 数据,并将其解析为我们所需的格式。请使用下面的 IronXL 解析器函数列表,选择适合您项目的函数。

数据类型方法说明
int工作表 ["CellAddress"].IntValue当我们需要将 Excel 单元格值解析为 `Int` 时使用它。
Int32工作表 ["CellAddress"].Int32Value当我们需要将 Excel 单元格值解析为 `Int32` 时。
Int64工作表 ["CellAddress"].Int64Value如果数值太大,而我们又想在项目中使用它。
浮动工作表 ["CellAddress"].FloatValue当数值在小数点后也很重要时使用。
双人WorkSheet ["CellAddress"].双人Value如果我们想获得精度更高的数值数据。
十进制WorkSheet ["CellAddress"].十进制Value如果小数点后的位数过多,而我们又想得到最精确的结果。

下面是一个示例,说明如何使用其中一些函数在 C# 中解析 Excel 文件数据。

/**
Parse into Numeric Values
anchor-parse-excel-data-into-numeric-values
**/
using IronXL;
static void Main(string [] args)
{
    WorkBook wb = WorkBook.Load("sample.xlsx");
    WorkSheet ws = wb.GetWorkSheet("Sheet1");
    //Parse Excel cell value into string
    string str_val = ws ["B3"].Value.ToString();
    //Parse Excel cell value into int32
    Int32 int32_val = ws ["G3"].Int32Value;
    //Parse Excel cell value into Decimal
    decimal decimal_val = ws ["E5"].DecimalValue;

    Console.WriteLine("Parse B3 Cell Value into String: {0}", str_val);
    Console.WriteLine("Parse G3 Cell Value into Int32: {0}", int32_val);
    Console.WriteLine("Parse E5 Cell Value into decimal: {0}", decimal_val);
    Console.ReadKey();
}
/**
Parse into Numeric Values
anchor-parse-excel-data-into-numeric-values
**/
using IronXL;
static void Main(string [] args)
{
    WorkBook wb = WorkBook.Load("sample.xlsx");
    WorkSheet ws = wb.GetWorkSheet("Sheet1");
    //Parse Excel cell value into string
    string str_val = ws ["B3"].Value.ToString();
    //Parse Excel cell value into int32
    Int32 int32_val = ws ["G3"].Int32Value;
    //Parse Excel cell value into Decimal
    decimal decimal_val = ws ["E5"].DecimalValue;

    Console.WriteLine("Parse B3 Cell Value into String: {0}", str_val);
    Console.WriteLine("Parse G3 Cell Value into Int32: {0}", int32_val);
    Console.WriteLine("Parse E5 Cell Value into decimal: {0}", decimal_val);
    Console.ReadKey();
}
'''
'''Parse into Numeric Values
'''anchor-parse-excel-data-into-numeric-values
'''*
Imports IronXL
Shared Sub Main(ByVal args() As String)
	Dim wb As WorkBook = WorkBook.Load("sample.xlsx")
	Dim ws As WorkSheet = wb.GetWorkSheet("Sheet1")
	'Parse Excel cell value into string
	Dim str_val As String = ws ("B3").Value.ToString()
	'Parse Excel cell value into int32
	Dim int32_val As Int32 = ws ("G3").Int32Value
	'Parse Excel cell value into Decimal
	Dim decimal_val As Decimal = ws ("E5").DecimalValue

	Console.WriteLine("Parse B3 Cell Value into String: {0}", str_val)
	Console.WriteLine("Parse G3 Cell Value into Int32: {0}", int32_val)
	Console.WriteLine("Parse E5 Cell Value into decimal: {0}", decimal_val)
	Console.ReadKey()
End Sub
VB   C#

该代码将显示以下输出:

我们可以在这里看到 Excel 文件 sample.xlsx 的值:


6.将 Excel 数据解析为布尔值

要将 Excel 文件数据解析为布尔数据类型,IronXL 提供了 BoolValue 函数。使用方法如下:

/**
Parse into Boolean Values
anchor-parse-excel-data-into-boolean-values
**/
bool Val = ws ["Cell Address"].BoolValue;
/**
Parse into Boolean Values
anchor-parse-excel-data-into-boolean-values
**/
bool Val = ws ["Cell Address"].BoolValue;
'''
'''Parse into Boolean Values
'''anchor-parse-excel-data-into-boolean-values
'''*
Dim Val As Boolean = ws ("Cell Address").BoolValue
VB   C#

ws是上述示例中描述的工作表。上述函数将返回truefalse`值。

注意:如果要将单元格值解析为布尔数据类型,请确保 Excel 文件值为 (0 ,1) 或 (True ,False) 格式。


7.将 Excel 文件解析为 C# 集合

使用 IronXL,我们可以将 Excel 文件数据解析为以下类型的 CSharp 集合:

数据类型方法说明
阵列WorkSheet ["From:To"].To阵列()该函数用于将 Excel 文件数据解析为数组。我们指定一个 Excel 文件单元格区域,将其数据转换为数组。
数据表WorkSheet.To数据表()It is used to parse a complete Excel worksheet into 数据表 and uses the data as we need.
数据集WorkBook.To数据集()we can parse a complete Excel WorkBook into a 数据集, in this way, the WorkSheets of Excel file becomes 数据表 of 数据集.

让我们逐一看看如何将 Excel 文件数据解析为这些集合类型的示例。

7.1.将 Excel 数据解析为数组

IronXL 提供了将指定范围的 Excel 文件数据解析为数组的简单方法。为此,我们需要指定 "From "到 "To "单元格地址,并将其数据转换为数组。具体操作如下

var array = WorkSheet ["From:To"].ToArray();
var array = WorkSheet ["From:To"].ToArray();
Dim array = WorkSheet ("From:To").ToArray()
VB   C#

如果要访问数组中的某个特定项目,我们可以使用

string item = array [ItemIndex].Value.ToString();
string item = array [ItemIndex].Value.ToString();
Dim item As String = array (ItemIndex).Value.ToString()
VB   C#

显然,我们可以通过索引轻松访问项目。让我们看看如何将 Excel 文件数据解析为数组并从中选择特定项的示例。

/**
Parse into Array
anchor-parse-excel-data-into-array
**/
using IronXL;
static void Main(string [] args)
{
    WorkBook wb = WorkBook.Load("sample.xlsx");
    WorkSheet ws = wb.GetWorkSheet("Sheet1");
    var array = ws ["B6:F6"].ToArray();
    int item = array.Count();
    string total_items = array [0].Value.ToString();
    Console.WriteLine("First item in the array: {0}", item);
    Console.WriteLine("Total items from B6 to F6: {0}",total_items);
    Console.ReadKey();
}
/**
Parse into Array
anchor-parse-excel-data-into-array
**/
using IronXL;
static void Main(string [] args)
{
    WorkBook wb = WorkBook.Load("sample.xlsx");
    WorkSheet ws = wb.GetWorkSheet("Sheet1");
    var array = ws ["B6:F6"].ToArray();
    int item = array.Count();
    string total_items = array [0].Value.ToString();
    Console.WriteLine("First item in the array: {0}", item);
    Console.WriteLine("Total items from B6 to F6: {0}",total_items);
    Console.ReadKey();
}
'''
'''Parse into Array
'''anchor-parse-excel-data-into-array
'''*
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 array = ws ("B6:F6").ToArray()
	Dim item As Integer = array.Count()
	Dim total_items As String = array (0).Value.ToString()
	Console.WriteLine("First item in the array: {0}", item)
	Console.WriteLine("Total items from B6 to F6: {0}",total_items)
	Console.ReadKey()
End Sub
VB   C#

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

Excel 文件 sample.xlsx 中从 B6F6 的范围值如下所示:

7.2.将 Excel 工作表解析为数据表

IronXL 的优势在于,我们可以轻松地将特定 Excel 工作表转换为数据表。为此,我们可以使用 `.ToDataTable()IronXL 的功能如下:

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

它将把 Excel 工作表解析为数据表 dt。在这种情况下,如果我们想使用 Excel 文件的第一行作为 DataTable 的列名,就可以这样设置:

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

ToDataTable 的布尔参数()函数将指定 Excel 文件的第一行成为 DataTable 的 ColumnName。您可以更深入地使用 在 C# 中将 ExcelWorksheet 作为 DataTable

下面是如何将 Excel 工作表解析为 DataTable 的示例:

/**
Parse into DataTable
anchor-parse-excel-worksheet-into-datatable
**/
using IronXL;
using System.Data; 
static void Main(string [] args)
{
    WorkBook wb = WorkBook.Load("sample.xlsx");
    WorkSheet ws = wb.GetWorkSheet("Sheet1");
    //parse sheet1 of sample.xlsx file into DataTable.
    //we set parameter true of ToDataTable() function,so first row of Excel file becomes columnname of DataTable
    DataTable dt = ws.ToDataTable(true); 
}
/**
Parse into DataTable
anchor-parse-excel-worksheet-into-datatable
**/
using IronXL;
using System.Data; 
static void Main(string [] args)
{
    WorkBook wb = WorkBook.Load("sample.xlsx");
    WorkSheet ws = wb.GetWorkSheet("Sheet1");
    //parse sheet1 of sample.xlsx file into DataTable.
    //we set parameter true of ToDataTable() function,so first row of Excel file becomes columnname of DataTable
    DataTable dt = ws.ToDataTable(true); 
}
'''
'''Parse into DataTable
'''anchor-parse-excel-worksheet-into-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")
	'parse sheet1 of sample.xlsx file into DataTable.
	'we set parameter true of ToDataTable() function,so first row of Excel file becomes columnname of DataTable
	Dim dt As DataTable = ws.ToDataTable(True)
End Sub
VB   C#

7.3.将 Excel 文件解析为数据集

如果我们要将完整的 Excel 文件解析为数据集,可以使用 .ToDataSet()IronXL 的 功能。使用方法如下:

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

注意:如果我们将 Excel 文件解析为数据集,那么 Excel 文件中的所有工作表都将成为该数据集的数据表。 让我们看看如何将 Excel 文件解析为 DataSet 的示例:

/**
Parse File into DataSet
anchor-parse-excel-file-into-dataset
**/
using IronXL;
using System.Data; 
static void Main(string [] args)
{
    WorkBook wb = WorkBook.Load("sample.xlsx");
    //parse WorkBook wb into DataSet
    DataSet ds = wb.ToDataSet(); 
    //we also can get DataTable from ds which is actually WorkSheet as:
    DataTable dt=ds.Tables [0];
}
/**
Parse File into DataSet
anchor-parse-excel-file-into-dataset
**/
using IronXL;
using System.Data; 
static void Main(string [] args)
{
    WorkBook wb = WorkBook.Load("sample.xlsx");
    //parse WorkBook wb into DataSet
    DataSet ds = wb.ToDataSet(); 
    //we also can get DataTable from ds which is actually WorkSheet as:
    DataTable dt=ds.Tables [0];
}
'''
'''Parse File into DataSet
'''anchor-parse-excel-file-into-dataset
'''*
Imports IronXL
Imports System.Data
Shared Sub Main(ByVal args() As String)
	Dim wb As WorkBook = WorkBook.Load("sample.xlsx")
	'parse WorkBook wb into DataSet
	Dim ds As DataSet = wb.ToDataSet()
	'we also can get DataTable from ds which is actually WorkSheet as:
	Dim dt As DataTable=ds.Tables (0)
End Sub
VB   C#

您可以阅读更多关于 Excel SQL 数据集 并使用这些文件。


教程快速访问

用 C# 编写 Excel 文档

使用 IronXL 文档在 C# 中处理 Excel,在您的项目中使用所有功能、类、命名空间等。

用 C# 编写 Excel 文档