使用IRONXL

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

更新 2024年一月6日
分享:

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

CSV 是什么?

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


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

在 MVC、ASP.NET 或 .NET Core 中使用 IronXL 读取 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 方法来指定 CSV 的名称及其格式,以及读取 CSV 文件时使用的分隔符。在本例中,逗号被用作分隔符。

A 工作表 对象。CSV 文件的内容就放置在这里。然后以新的名称和格式保存文件。

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

数据在 Microsoft Excel 中显示


2.IronXL for 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 "工作表 "作为数据表进行操作非常简单。

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 对象访问工作表名称

从数据集对象访问工作表名称

我们再来看一个如何访问所有 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#.NET中的CSV解析

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

6.以 C#记录读取 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 的控制台输出

数据表的控制台输出

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

8.如何用 C&num 解析 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 提供了 布尔值 功能。其使用方法如下:

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 工作表转换为数据表。为此,我们可以使用 .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 文件数据。该范围可应用于行和列。

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 中的数据

*样本.xlsx中的数据显示

此外,IronXL 还兼容 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 数据。

通过该应用程序接口,我们可以直观地创建、读取、操作、保存和导出 Excel 文件:

  1. .NET Framework 4.5 以上

  2. .NET Core 2+

  3. .NET 标准

4.Xamarin

5.Windows 移动

6.单声道

  1. Azure 云主机

  2. Blazor

  3. .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.结论与铁 XL 特别优惠

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

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

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

5 种铁套房产品

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

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

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