使用IRONXL

在C#中读取CSV文件:教程

更新 2024年一月6日
分享:

在使用各种 Excel 格式时,经常需要读取数据,然后以编程方式重新配置。 在本文中,我们将学习如何使用 IronXL.Excel 这个完美的工具,用 C# 阅读 CSV 文件并解析 Excel 电子表格中的数据。

什么是 CSV?

CSV 是一种简单的数据格式,但也会有很多不同之处,但在我们的 C# 项目中很难通过编程读取它,因为它使用了多种分隔符来区分数据的行和列。 本文将向您展示如何使用IronXL 图书馆读取 CSV 文件。


1.如何在 C# 中读取 CSV 文件;

在利用 IronXL for .NET 读取 MVC、ASP.NET 或 .NET Core 中的 CSV 文件之前,您需要安装它。 以下是快速浏览。

  1. 在 Visual Studio 中,选择“项目”菜单。

  2. 管理 NuGet 软件包

  3. 搜索 IronXL.Excel

  4. 安装

    用 C# 阅读 CSV 文件:教程,图 1:在 Visual Studio 的 NuGet 包管理器中搜索 IronXL

    在 Visual Studio 的 NuGet 包管理器中搜索 IronXL

    当您需要用 C# 阅读 CSV 文件时,IronXL 就是您的最佳工具。 您可以读取带有逗号或任何其他分隔符的CSV文件,如下面的代码段所示。

WorkBook workbook = WorkBook.LoadCSV("Weather.csv", fileFormat: ExcelFileFormat.XLSX, ListDelimiter: ",");
WorkSheet ws = workbook.DefaultWorkSheet;
workbook.SaveAs("Csv_To_Excel.xlsx");
WorkBook workbook = WorkBook.LoadCSV("Weather.csv", fileFormat: ExcelFileFormat.XLSX, ListDelimiter: ",");
WorkSheet ws = workbook.DefaultWorkSheet;
workbook.SaveAs("Csv_To_Excel.xlsx");
Dim workbook As WorkBook = WorkBook.LoadCSV("Weather.csv", fileFormat:= ExcelFileFormat.XLSX, ListDelimiter:= ",")
Dim ws As WorkSheet = workbook.DefaultWorkSheet
workbook.SaveAs("Csv_To_Excel.xlsx")
VB   C#

输出:

用 C# 阅读 CSV 文件:教程,图 2:用逗号分隔符输出 CSV 文件

输出带逗号分隔符的 CSV 文件

代码解释:

A工作簿创建对象。 "(《世界人权宣言》)加载CSV然后,我们将使用 WorkBook 对象的方法来指定 CSV 的名称及其格式,即在读取的 CSV 文件中使用哪些分隔符。 在本例中,逗号被用作分隔符。

A工作表然后创建对象。 这是将放置CSV文件内容的位置。 然后将文件以新的名称和格式保存。

用 C# 阅读 CSV 文件:教程,图 3:Microsoft Excel 中显示的数据

数据在 Microsoft Excel 中显示


2.IronXL.Excel 文件

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

Install-Package IronXL.Excel

3.加载 WorkBook 和访问 WorkSheet

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

WorkBook wb = WorkBook.Load("sample.xlsx");//Excel file path
WorkBook wb = WorkBook.Load("sample.xlsx");//Excel file path
Dim wb As WorkBook = WorkBook.Load("sample.xlsx") 'Excel file path
VB   C#

要访问 Excel 文件的特定工作表,IronXL 提供了 WorkSheet 类。

WorkSheet ws = wb.GetWorkSheet("Sheet1"); //by sheet name
WorkSheet ws = wb.GetWorkSheet("Sheet1"); //by sheet name
Dim ws As WorkSheet = wb.GetWorkSheet("Sheet1") 'by sheet name
VB   C#

一旦获得 Excel 工作表 ws,您就可以从中提取任何类型的数据并执行所有 Excel 函数。 在此过程中,可从 Excel 工作表 ws 中获取数据:

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();
}
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();
}
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#

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

使用 IronXL.Excel,可以非常方便地将 Excel WorkSheet 作为 DataTable 进行操作。

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

使用以下命名空间

using IronXL;
using System.Data;
using IronXL;
using System.Data;
Imports IronXL
Imports System.Data
VB   C#

编写以下代码

static void Main(string [] args)
{
    WorkBook wb = WorkBook.Load("Weather.xlsx"); // Your Excel file Name
    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] + "  ");
        }
        Console.WriteLine();
    }
}
static void Main(string [] args)
{
    WorkBook wb = WorkBook.Load("Weather.xlsx"); // Your Excel file Name
    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] + "  ");
        }
        Console.WriteLine();
    }
}
Shared Sub Main(ByVal args() As String)
	Dim wb As WorkBook = WorkBook.Load("Weather.xlsx") ' Your Excel file Name
	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
		Console.WriteLine()
	Next row
End Sub
VB   C#

用 C# 阅读 CSV 文件:教程,图 4:DataTable 对象的控制台输出

数据表对象的控制台输出

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

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);
    }
}
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);
    }
}
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#

用 C# 阅读 CSV 文件:教程,图 5:从 DataSet 对象访问工作表名称

从 DataSet 对象访问工作表名称

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

static void Main(string [] args)
{
    WorkBook wb = WorkBook.Load("Weather.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] + "  ");
            }
            Console.WriteLine();
        }
    }
}
static void Main(string [] args)
{
    WorkBook wb = WorkBook.Load("Weather.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] + "  ");
            }
            Console.WriteLine();
        }
    }
}
Shared Sub Main(ByVal args() As String)
	Dim wb As WorkBook = WorkBook.Load("Weather.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
			Console.WriteLine()
		Next row
	Next dt
End Sub
VB   C#

用 C# 阅读 CSV 文件:教程,图 6:数据集对象的控制台输出

数据集对象的控制台输出

5.C# 中的 CSV 解析;.NET

CSV 在字段中如何处理换行符,或者字段如何包含在完全阻止简单字符串拆分方法的引号中,都存在大量问题。 最近,我在 C# .NET 中转换 CSV 时发现了以下选项,即指定一个可自定义的分隔符,而不是使用 `string.Split(',')用逗号分隔数值。

6.在 C# Records 中读取 CSV 数据

通过这一过程,读者可以阅读下一个文件。我们在 trygetfield 中读取 CSV 字段文件。 我们将 CSV 文件中的字段作为记录字段使用读取功能。

WorkBook workbook = WorkBook.LoadCSV("Weather.csv", fileFormat: ExcelFileFormat.XLSX, ListDelimiter: ",");
WorkSheet ws = workbook.DefaultWorkSheet;
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] + "  ");
    }
    Console.WriteLine();
}
WorkBook workbook = WorkBook.LoadCSV("Weather.csv", fileFormat: ExcelFileFormat.XLSX, ListDelimiter: ",");
WorkSheet ws = workbook.DefaultWorkSheet;
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] + "  ");
    }
    Console.WriteLine();
}
Dim workbook As WorkBook = WorkBook.LoadCSV("Weather.csv", fileFormat:= ExcelFileFormat.XLSX, ListDelimiter:= ",")
Dim ws As WorkSheet = workbook.DefaultWorkSheet
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
	Console.WriteLine()
Next row
VB   C#

用 C# 阅读 CSV 文件:教程,图 7:DataTable 的控制台输出

DataTable 的控制台输出

7.从 Excel 文件中获取数据

现在,我们可以使用各种方法从打开的 Excel 工作表中轻松获取任何类型的数据。 在下面的示例中,我们可以看到如何访问特定单元格值并将其解析为 string

//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 文件数据.

8.如何用 C# 解析 Excel 文件;

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

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();
}
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();
}
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#

9.如何将 Excel 数据解析为数值和布尔值

现在我们来看如何解析Excel文件数据。 首先,我们要了解如何处理 Excel 数字数据,然后将其解析为我们所需的格式。

用 C# 阅读 CSV 文件:教程,图 8:每种数据类型的汇总表

每种数据类型的摘要表

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();
}
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();
}
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#

该代码将显示以下输出:

用 C# 阅读 CSV 文件:教程,图 9:控制台输出正确的数据类型

带有正确数据类型的控制台输出

我们可以在此查看 Excel 文件 sample.xlsx 的值:

用 C# 阅读 CSV 文件:教程,图 10:在 Excel 中显示正确的数据类型

在 Excel 中显示正确的数据类型

为将 Excel 文件数据解析为布尔数据类型,IronXL.Excel 提供了布尔值功能。 它可以如下使用:

bool Val = ws ["Cell Address"].BoolValue;
bool Val = ws ["Cell Address"].BoolValue;
Dim Val As Boolean = ws ("Cell Address").BoolValue
VB   C#

10.如何将 Excel 文件解析为 C&num;集合

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();
}
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();
}
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#

10.1 如何将 ExcelWorkSheet 解析为数据表

IronXL.Excel 的一个出色功能是,我们可以轻松地将特定的 Excel WorkSheet 转换为 DataTable。 为此,我们可以使用.ToDataTable()IronXL 的功能如下

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);
}
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);
}
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#

10.2 如何将 Excel 文件解析为数据集

如果我们想将一个完整的 Excel 文件解析为一个数据集,可以使用.ToDataSet()`。功能。

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];
}
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];
}
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#

10.3 读取特定范围内的 Excel 数据

IronXL.Excel 提供了一种智能方法,用于读取特定范围内的 Excel 文件数据。 该范围可适用于行和列。

static void Main(string [] args)
{
    WorkBook wb = WorkBook.Load("sample.xlsx");
    WorkSheet ws = wb.GetWorkSheet("Sheet1");
    //get specified range values by loop
    foreach (var item in ws ["B3:B8"])
    {
        Console.WriteLine("Value is: {0}", item);
    }
    Console.ReadKey();
}
static void Main(string [] args)
{
    WorkBook wb = WorkBook.Load("sample.xlsx");
    WorkSheet ws = wb.GetWorkSheet("Sheet1");
    //get specified range values by loop
    foreach (var item in ws ["B3:B8"])
    {
        Console.WriteLine("Value is: {0}", item);
    }
    Console.ReadKey();
}
Shared Sub Main(ByVal args() As String)
	Dim wb As WorkBook = WorkBook.Load("sample.xlsx")
	Dim ws As WorkSheet = wb.GetWorkSheet("Sheet1")
	'get specified range values by loop
	For Each item In ws ("B3:B8")
		Console.WriteLine("Value is: {0}", item)
	Next item
	Console.ReadKey()
End Sub
VB   C#

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

用 C# 阅读 CSV 文件:教程,图 11:访问范围 B3:B8 中所有值的控制台输出

控制台输出以访问范围 B3:B8 中的所有值

并生成 Excel 文件 sample.xlsx 值:

用 C# 阅读 CSV 文件:教程,图 12:显示 sample.xlsx 中的数据

数据显示来自 sample.xlsx

此外,IronXL.Excel 还与许多 Excel 方法兼容,可与单元格进行交互,包括造型和边框, 数学功能, [条件格式化或根据现有数据创建图表。

11.如何读取 Excel 文件中的布尔数据

在应用程序开发中,我们需要根据 Excel 文件中的布尔数据类型做出决策。

static void Main(string [] args)
{
   WorkBook wb = WorkBook.Load("sample.xlsx");
   WorkSheet ws = wb.GetWorkSheet("Sheet1");
   foreach (var item in ws ["G1:G10"])
   {
   Console.WriteLine("  Condition is: {0}", item.BoolValue);
   }
   Console.ReadKey();
}
static void Main(string [] args)
{
   WorkBook wb = WorkBook.Load("sample.xlsx");
   WorkSheet ws = wb.GetWorkSheet("Sheet1");
   foreach (var item in ws ["G1:G10"])
   {
   Console.WriteLine("  Condition is: {0}", item.BoolValue);
   }
   Console.ReadKey();
}
Shared Sub Main(ByVal args() As String)
   Dim wb As WorkBook = WorkBook.Load("sample.xlsx")
   Dim ws As WorkSheet = wb.GetWorkSheet("Sheet1")
   For Each item In ws ("G1:G10")
   Console.WriteLine("  Condition is: {0}", item.BoolValue)
   Next item
   Console.ReadKey()
End Sub
VB   C#

由此,我们得到了输出结果:

用 C# 阅读 CSV 文件:教程,图 13:获取布尔数据的控制台输出

获取布尔数据的控制台输出

以及包含 C1 至 C10 值的 Excel 文件 sample.xlsx:

用 C# 阅读 CSV 文件:教程,图 14:Excel 示例与控制台输出比较

与控制台输出进行比较的 Excel 样本

12.如何阅读完整的 Excel 工作表

通过使用行和列索引,可以轻松读取完整的Excel工作表。 为此,我们使用了两个循环:一个用于遍历所有行,第二个用于遍历特定行的所有列。 然后,我们就可以轻松获取整个 Excel 工作表中的所有单元格值。

static void Main(string [] args)
{
    WorkBook wb = WorkBook.Load("Weather.xlsx"); // your Excel File Name
    WorkSheet ws = wb.GetWorkSheet("Sheet1");
    //Traverse all rows of Excel WorkSheet
    for (int i = 0;  i< ws.Rows.Count(); i++)
    {
        //Traverse all columns of specific Row
        for (int j = 0; j < ws.Columns.Count(); j++)
        {
            //Get the values
            string val = ws.Rows [i].Columns [j].Value.ToString();
            Console.WriteLine("Value of Row {0} and Column {1} is: {2}", i, j,val);
        }
    }
    Console.ReadKey();
}
static void Main(string [] args)
{
    WorkBook wb = WorkBook.Load("Weather.xlsx"); // your Excel File Name
    WorkSheet ws = wb.GetWorkSheet("Sheet1");
    //Traverse all rows of Excel WorkSheet
    for (int i = 0;  i< ws.Rows.Count(); i++)
    {
        //Traverse all columns of specific Row
        for (int j = 0; j < ws.Columns.Count(); j++)
        {
            //Get the values
            string val = ws.Rows [i].Columns [j].Value.ToString();
            Console.WriteLine("Value of Row {0} and Column {1} is: {2}", i, j,val);
        }
    }
    Console.ReadKey();
}
Shared Sub Main(ByVal args() As String)
	Dim wb As WorkBook = WorkBook.Load("Weather.xlsx") ' your Excel File Name
	Dim ws As WorkSheet = wb.GetWorkSheet("Sheet1")
	'Traverse all rows of Excel WorkSheet
	For i As Integer = 0 To ws.Rows.Count() - 1
		'Traverse all columns of specific Row
		For j As Integer = 0 To ws.Columns.Count() - 1
			'Get the values
			Dim val As String = ws.Rows (i).Columns (j).Value.ToString()
			Console.WriteLine("Value of Row {0} and Column {1} is: {2}", i, j,val)
		Next j
	Next i
	Console.ReadKey()
End Sub
VB   C#

在 C# 中读取 CSV 文件:教程,图 15:读取所有值的控制台输出

读取所有值后的控制台输出

13.如何在不进行互操作的情况下读取 Excel 文件

IronXL 是一个适用于 C# 的 Excel 库该工具允许开发人员在不使用 Microsoft.Office.Interop.Excel* 的情况下,从 XLS 和 XLSX 文档中读取和编辑 Excel 数据。

通过 API,我们可以直观地创建、读取、操作、保存和导出 Excel 文件:

  1. .NET Framework 4.5 以上

  2. .NET Core 2+

  3. .NET标准

    4.Xamarin

  4. 视窗移动

    6.单声道

  5. Azure 云主机

  6. Blazor

  7. .NET MAUI

    添加以下命名空间:

using IronXL;
using System;
using System.Linq;
using IronXL;
using System;
using System.Linq;
Imports IronXL
Imports System
Imports System.Linq
VB   C#

现在在主函数中编写以下代码。

WorkBook workbook = WorkBook.Load("Weather.xlsx");
WorkSheet sheet = workbook.WorkSheets.First();

//Select cells easily in Excel notation and return the calculated value
int cellValue = sheet ["A2"].IntValue;
// Read from Ranges of cells elegantly.
foreach (var cell in sheet ["A2:A10"])
{
   Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text);
}
WorkBook workbook = WorkBook.Load("Weather.xlsx");
WorkSheet sheet = workbook.WorkSheets.First();

//Select cells easily in Excel notation and return the calculated value
int cellValue = sheet ["A2"].IntValue;
// Read from Ranges of cells elegantly.
foreach (var cell in sheet ["A2:A10"])
{
   Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text);
}
Dim workbook As WorkBook = WorkBook.Load("Weather.xlsx")
Dim sheet As WorkSheet = workbook.WorkSheets.First()

'Select cells easily in Excel notation and return the calculated value
Dim cellValue As Integer = sheet ("A2").IntValue
' Read from Ranges of cells elegantly.
For Each cell In sheet ("A2:A10")
   Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text)
Next cell
VB   C#

用 C# 阅读 CSV 文件:教程,图 16:每个单元格的控制台输出

每个单元的控制台输出

IronXL 还完全支持 ASP.NET、MVC、Windows、macOS、Linux、iOS 和 Android 移动应用程序开发。

14.结论和 Iron XL 特别优惠

除外CSV 解析只需两行代码,IronXL 就能用 C# 将 CSV 文件转换为 Excel 文件!

使用 C# 或 VB.NET,无需 Interop 即可非常轻松地使用 IronXL's Excel API。您可以读取、编辑和创建 Excel 电子表格,或使用其他 Excel 格式,如xls/xlsx/csv/tsv. 由于支持多个框架,您可以用两个框架的价格购买 5 个产品。 点击我们的定价页面如需更多信息,请联系

用 C# 阅读 CSV 文件:教程,图 17:Iron Suite 的 5 种产品

Iron Suite 的 5 种产品**

< 前一页
如何在Excel中突出显示每隔一行
下一步 >
如何锁定Excel单元格:逐步教程

准备开始了吗? 版本: 2024.11 刚刚发布

免费NuGet下载 总下载量: 1,111,773 查看许可证 >