C# 读取 Excel 文件教程

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

克里斯蒂安·费因德莱

本教程介绍如何用 C&num 读取 Excel 文件,以及执行数据验证、数据库转换、Web API 集成和公式修改等日常任务。本文引用了使用 IronXL .NET Excel 库的代码示例。


概述

IronXL 可使用 C&num 方便地读取和编辑 Microsoft Excel 文档。IronXL 既不需要 Microsoft Excel,也不需要 互操作.事实上 IronXL 提供了比 "Microsoft.Office.Interop.Excel "更快、更直观的应用程序接口.

IronXL Includes:

  • 我们的 .NET 工程师提供的专门产品支持
  • 通过 Microsoft Visual Studio 轻松安装

  • 用于开发的免费试用测试。许可证来自 $599。

使用 IronXL 软件库,在 C&num 和 VB.NET 中轻松读取和创建 Excel 文件。

使用 IronXL 读取 .XLS 和 .XLSX Excel 文件

以下是使用 IronXL 读取 Excel 文件的整体工作流程摘要:

1.安装 IronXL Excel 库。我们可以使用 NuGet 软件包 或下载 .Net Excel DLL.

2.使用 WorkBook.Load 方法读取任何 XLS、XLSX 或 CSV 文档。

3.使用直观的语法获取单元格值:表格 ["A11"].DecimalValue`

:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-1.cs
using IronXL;
using System;
using System.Linq;

// Supported spreadsheet formats for reading include: XLSX, XLS, CSV and TSV
WorkBook workBook = WorkBook.Load("test.xlsx");
WorkSheet workSheet = workBook.WorkSheets.First();

// Select cells easily in Excel notation and return the calculated value
int cellValue = workSheet["A2"].IntValue;

// Read from Ranges of cells elegantly.
foreach (var cell in workSheet["A2:A10"])
{
    Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text);
}

// Advanced Operations
// Calculate aggregate values such as Min, Max and Sum
decimal sum = workSheet["A2:A10"].Sum();

// Linq compatible
decimal max = workSheet["A2:A10"].Max(c => c.DecimalValue);
Imports IronXL
Imports System
Imports System.Linq

' Supported spreadsheet formats for reading include: XLSX, XLS, CSV and TSV
Private workBook As WorkBook = WorkBook.Load("test.xlsx")
Private workSheet As WorkSheet = workBook.WorkSheets.First()

' Select cells easily in Excel notation and return the calculated value
Private cellValue As Integer = workSheet("A2").IntValue

' Read from Ranges of cells elegantly.
For Each cell In workSheet("A2:A10")
	Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text)
Next cell

' Advanced Operations
' Calculate aggregate values such as Min, Max and Sum
Dim sum As Decimal = workSheet("A2:A10").Sum()

' Linq compatible
Dim max As Decimal = workSheet("A2:A10").Max(Function(c) c.DecimalValue)
VB   C#

本教程后续章节中使用的代码示例 (以及示例项目代码) 将在三个 Excel 电子表格样本上运行 (见下图):


教程

1. 免费下载 IronXL C# 库

适用于Excel的C# NuGet库

安装使用 NuGet

Install-Package IronXL.Excel
Java PDF JAR

下载 DLL

下载DLL

手动安装到你的项目中

适用于Excel的C# NuGet库

安装使用 NuGet

Install-Package IronXL.Excel
Java PDF JAR

下载 DLL

下载DLL

手动安装到你的项目中

开始在您的项目中使用IronPDF,并立即获取免费试用。

第一步:
green arrow pointer

查看 IronXLNuget 用于快速安装和部署。它有超过800万次下载,正在使用C#改变Excel。

适用于Excel的C# NuGet库 nuget.org/packages/IronXL.Excel/
Install-Package IronXL.Excel

考虑安装 IronXL DLL 直接。下载并手动安装到您的项目或GAC表单中: IronXL.zip

手动安装到你的项目中

下载DLL

首先,我们需要安装 IronXL.Excel 库,为 .NET 框架添加 Excel 功能。

安装 IronXL.Excel 最方便的方式是使用我们的 NuGet 包,当然你也可以选择手动安装。 DLL 到项目或全局程序集缓存中。

安装 IronXL NuGet 软件包

1.在 Visual Studio 中,右键单击项目,选择 "管理 NuGet 包..."。

2.搜索 IronXL.Excel 软件包,点击安装按钮将其添加到项目中

另一种安装 IronXL 库的方法是使用 NuGet 包管理器控制台:

1.进入软件包管理器控制台

2.键入 > 安装软件包 IronXL.Excel.

  PM > Install-Package IronXL.Excel

此外,您还可以 在 NuGet 网站上查看软件包

手动安装

或者,我们可以先下载 IronXL .NET Excel DLL 并手动安装到 Visual Studio。

2.加载 Excel 工作簿

加载 Excel 工作簿 工作簿 类表示 Excel 工作表。要使用 C&num 打开 Excel 文件,我们使用WorkBook.Load方法,指定 Excel 文件的路径。

:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-2.cs
WorkBook workBook = WorkBook.Load(@"Spreadsheets\\GDP.xlsx");
Dim workBook As WorkBook = WorkBook.Load("Spreadsheets\\GDP.xlsx")
VB   C#

样本 ExcelToDBProcessor

每个 "工作簿 "可以有多个 工作表 对象。每个对象代表 Excel 文档中的一个 Excel 工作表。使用 工作簿.获取工作表 方法获取特定 Excel 工作表的引用。


:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-3.cs

样本 ExcelToDB

创建新的 Excel 文档

要创建一个新的 Excel 文档,请使用有效的文件类型构建一个新的 WorkBook 对象。

:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-4.cs
WorkBook workBook = new WorkBook(ExcelFileFormat.XLSX);
Dim workBook As New WorkBook(ExcelFileFormat.XLSX)
VB   C#

样本 ApiToExcelProcessor

注意:使用 ExcelFileFormat.XLS 以支持 Microsoft Excel 的旧版本 (95 及更早).

在 Excel 文档中添加工作表

如前所述,IronXL "工作簿 "包含一个或多个 "工作表 "的集合。

这就是 Excel 中包含两个工作表的工作簿的样子。

这就是 Excel 中包含两个工作表的工作簿的样子。

要创建新的工作表,请调用 WorkBook.CreateWorkSheet 并输入工作表的名称。

:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-5.cs
WorkSheet workSheet = workBook.GetWorkSheet("GDPByCountry");
Dim workSheet As WorkSheet = workBook.GetWorkSheet("GDPByCountry")
VB   C#

3.访问单元格值

读取和编辑单个单元格

访问单个电子表格单元格的值时,需要从其 "工作表 "中检索所需的单元格,如下所示:

:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-16.cs
WorkBook workBook = WorkBook.Load("test.xlsx");
WorkSheet workSheet = workBook.DefaultWorkSheet;
IronXL.Cell cell = workSheet["B1"].First();
Dim workBook As WorkBook = WorkBook.Load("test.xlsx")
Dim workSheet As WorkSheet = workBook.DefaultWorkSheet
Dim cell As IronXL.Cell = workSheet("B1").First()
VB   C#

IronXL's 单元格 类表示 Excel 电子表格中的一个单独单元格。它包含的属性和方法可使用户直接访问和修改单元格的值。

每个 WorkSheet 对象都管理着一个与 Excel 工作表中每个单元格值相对应的 Cell 对象索引。在上面的源代码中,我们通过行和列的索引来引用所需的单元格 (本例中的单元格 B1) 使用标准数组索引语法。

通过对 Cell 对象的引用,我们可以读写电子表格单元格中的数据:

:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-17.cs
IronXL.Cell cell = workSheet["B1"].First();
string value = cell.StringValue;   // Read the value of the cell as a string
Console.WriteLine(value);

cell.Value = "10.3289";           // Write a new value to the cell
Console.WriteLine(cell.StringValue);
Dim cell As IronXL.Cell = workSheet("B1").First()
Dim value As String = cell.StringValue ' Read the value of the cell as a string
Console.WriteLine(value)

cell.Value = "10.3289" ' Write a new value to the cell
Console.WriteLine(cell.StringValue)
VB   C#

读写单元格数值范围

Range "类表示一个由 "单元格 "对象组成的二维集合。该集合指的是 Excel 单元格的字面范围。通过在WorkSheet对象上使用字符串索引器来获取范围。

参数文本可以是单元格的坐标 (例如 "A1",如前所示) 或从左到右从上到下的单元格跨度 (例如:"B2:E5"). 也可以在WorkSheet上调用GetRange

:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-6.cs
Range range = workSheet["D2:D101"];
Dim range As Range = workSheet("D2:D101")
VB   C#

样本: 数据验证

有几种方法可以读取或编辑范围内单元格的值。如果已知计数,则使用 For 循环。

:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-7.cs
// Iterate through the rows
for (var y = 2; y <= 101; y++)
{
    var result = new PersonValidationResult { Row = y };
    results.Add(result);

    // Get all cells for the person
    var cells = workSheet[$"A{y}:E{y}"].ToList();

    // Validate the phone number (1 = B)
    var phoneNumber = cells[1].Value;
    result.PhoneNumberErrorMessage = ValidatePhoneNumber(phoneNumberUtil, (string)phoneNumber);

    // Validate the email address (3 = D)
    result.EmailErrorMessage = ValidateEmailAddress((string)cells[3].Value);

    // Get the raw date in the format of Month Day[suffix], Year (4 = E)
    var rawDate = (string)cells[4].Value;
    result.DateErrorMessage = ValidateDate(rawDate);
}
' Iterate through the rows
For y = 2 To 101
	Dim result = New PersonValidationResult With {.Row = y}
	results.Add(result)

	' Get all cells for the person
	Dim cells = workSheet($"A{y}:E{y}").ToList()

	' Validate the phone number (1 = B)
	Dim phoneNumber = cells(1).Value
	result.PhoneNumberErrorMessage = ValidatePhoneNumber(phoneNumberUtil, CStr(phoneNumber))

	' Validate the email address (3 = D)
	result.EmailErrorMessage = ValidateEmailAddress(CStr(cells(3).Value))

	' Get the raw date in the format of Month Day[suffix], Year (4 = E)
	Dim rawDate = CStr(cells(4).Value)
	result.DateErrorMessage = ValidateDate(rawDate)
Next y
VB   C#

样本: 数据验证

在电子表格中添加公式

公式 财产

下面的代码会遍历每个州,并在 C 栏中输入总百分比。

:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-13.cs
// Iterate through all rows with a value
for (var y = 2 ; y < i ; y++)
{
    // Get the C cell
    Cell cell = workSheet[$"C{y}"].First();

    // Set the formula for the Percentage of Total column
    cell.Formula = $"=B{y}/B{i}";
}
' Iterate through all rows with a value
Dim y = 2
Do While y < i
	' Get the C cell
	Dim cell As Cell = workSheet($"C{y}").First()

	' Set the formula for the Percentage of Total column
	cell.Formula = $"=B{y}/B{i}"
	y += 1
Loop
VB   C#

样本 AddFormulaeProcessor

验证电子表格数据

使用 IronXL 验证数据表。数据验证 "示例使用 "libphonenumber-csharp "来验证电话号码,并使用标准 C# API 来验证电子邮件地址和日期。

:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-8.cs
// Iterate through the rows
for (var i = 2; i <= 101; i++)
{
    var result = new PersonValidationResult { Row = i };
    results.Add(result);

    // Get all cells for the person
    var cells = worksheet[$"A{i}:E{i}"].ToList();

    // Validate the phone number (1 = B)
    var phoneNumber = cells[1].Value;
    result.PhoneNumberErrorMessage = ValidatePhoneNumber(phoneNumberUtil, (string)phoneNumber);

    // Validate the email address (3 = D)
    result.EmailErrorMessage = ValidateEmailAddress((string)cells[3].Value);

    // Get the raw date in the format of Month Day[suffix], Year (4 = E)
    var rawDate = (string)cells[4].Value;
    result.DateErrorMessage = ValidateDate(rawDate);
}
' Iterate through the rows
For i = 2 To 101
	Dim result = New PersonValidationResult With {.Row = i}
	results.Add(result)

	' Get all cells for the person
	Dim cells = worksheet($"A{i}:E{i}").ToList()

	' Validate the phone number (1 = B)
	Dim phoneNumber = cells(1).Value
	result.PhoneNumberErrorMessage = ValidatePhoneNumber(phoneNumberUtil, CStr(phoneNumber))

	' Validate the email address (3 = D)
	result.EmailErrorMessage = ValidateEmailAddress(CStr(cells(3).Value))

	' Get the raw date in the format of Month Day[suffix], Year (4 = E)
	Dim rawDate = CStr(cells(4).Value)
	result.DateErrorMessage = ValidateDate(rawDate)
Next i
VB   C#

上述代码循环查看电子表格中的每一行,并以列表形式抓取单元格。每个 validates 方法都会检查单元格的值,如果值无效,则返回错误信息。

这段代码将创建一个新工作表,指定页眉,并输出错误信息结果,以便记录无效数据。

:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-9.cs
var resultsSheet = workBook.CreateWorkSheet("Results");
resultsSheet["A1"].Value = "Row";
resultsSheet["B1"].Value = "Valid";
resultsSheet["C1"].Value = "Phone Error";
resultsSheet["D1"].Value = "Email Error";
resultsSheet["E1"].Value = "Date Error";
for (var i = 0; i < results.Count; i++)
{
    var result = results[i];
    resultsSheet[$"A{i + 2}"].Value = result.Row;
    resultsSheet[$"B{i + 2}"].Value = result.IsValid ? "Yes" : "No";
    resultsSheet[$"C{i + 2}"].Value = result.PhoneNumberErrorMessage;
    resultsSheet[$"D{i + 2}"].Value = result.EmailErrorMessage;
    resultsSheet[$"E{i + 2}"].Value = result.DateErrorMessage;
}
workBook.SaveAs(@"Spreadsheets\\PeopleValidated.xlsx");
Dim resultsSheet = workBook.CreateWorkSheet("Results")
resultsSheet("A1").Value = "Row"
resultsSheet("B1").Value = "Valid"
resultsSheet("C1").Value = "Phone Error"
resultsSheet("D1").Value = "Email Error"
resultsSheet("E1").Value = "Date Error"
For i = 0 To results.Count - 1
	Dim result = results(i)
	resultsSheet($"A{i + 2}").Value = result.Row
	resultsSheet($"B{i + 2}").Value = If(result.IsValid, "Yes", "No")
	resultsSheet($"C{i + 2}").Value = result.PhoneNumberErrorMessage
	resultsSheet($"D{i + 2}").Value = result.EmailErrorMessage
	resultsSheet($"E{i + 2}").Value = result.DateErrorMessage
Next i
workBook.SaveAs("Spreadsheets\\PeopleValidated.xlsx")
VB   C#

4.使用实体框架导出数据

使用 IronXL 将数据导出到数据库或将 Excel 电子表格转换为数据库。ExcelToDB "示例读取按国家分列的国内生产总值电子表格,然后将数据导出到 SQLite。

它使用 EntityFramework 构建数据库,然后逐行导出数据。

添加 SQLite Entity Framework NuGet 软件包。

EntityFramework "允许您创建一个可向数据库导出数据的模型对象。

:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-10.cs
public class Country
    {
        [Key]
        public Guid Key { get; set; }
        public string Name { get; set; }
        public decimal GDP { get; set; }
    }
Public Class Country
		<Key>
		Public Property Key() As Guid
		Public Property Name() As String
		Public Property GDP() As Decimal
End Class
VB   C#

要使用不同的数据库,请安装相应的 NuGet 软件包,并找到与 UseSqLite()

:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-11.cs
public class CountryContext : DbContext
    {
        public DbSet<Country> Countries { get; set; }
        public CountryContext()
        {
            //TODO: Make async
            Database.EnsureCreated();
        }
        /// <summary>
        /// Configure context to use Sqlite
        /// </summary>
        /// <param name="optionsBuilder"></param>
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            var connection = new SqliteConnection($"Data Source=Country.db");
            connection.Open();
            var command = connection.CreateCommand();
            //Create the database if it doesn't already exist
            command.CommandText = $"PRAGMA foreign_keys = ON;";
            command.ExecuteNonQuery();
            optionsBuilder.UseSqlite(connection);
            base.OnConfiguring(optionsBuilder);
        }
    }
Public Class CountryContext
	Inherits DbContext

		Public Property Countries() As DbSet(Of Country)
		Public Sub New()
			'TODO: Make async
			Database.EnsureCreated()
		End Sub
		''' <summary>
		''' Configure context to use Sqlite
		''' </summary>
		''' <param name="optionsBuilder"></param>
		Protected Overrides Sub OnConfiguring(ByVal optionsBuilder As DbContextOptionsBuilder)
			Dim connection = New SqliteConnection($"Data Source=Country.db")
			connection.Open()
			Dim command = connection.CreateCommand()
			'Create the database if it doesn't already exist
			command.CommandText = $"PRAGMA foreign_keys = ON;"
			command.ExecuteNonQuery()
			optionsBuilder.UseSqlite(connection)
			MyBase.OnConfiguring(optionsBuilder)
		End Sub
End Class
VB   C#

创建一个CountryContext,遍历范围以创建每条记录,然后SaveAsync向数据库提交数据

:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-12.cs
public async Task ProcessAsync()
{
    //Get the first worksheet
    var workbook = WorkBook.Load(@"Spreadsheets\\GDP.xlsx");
    var worksheet = workbook.GetWorkSheet("GDPByCountry");
    //Create the database connection
    using (var countryContext = new CountryContext())
    {
        //Iterate through all the cells
        for (var i = 2; i <= 213; i++)
        {
            //Get the range from A-B
            var range = worksheet[$"A{i}:B{i}"].ToList();
            //Create a Country entity to be saved to the database
            var country = new Country
            {
                Name = (string)range[0].Value,
                GDP = (decimal)(double)range[1].Value
            };
            //Add the entity
            await countryContext.Countries.AddAsync(country);
        }
        //Commit changes to the database
        await countryContext.SaveChangesAsync();
    }
}
Public Async Function ProcessAsync() As Task
	'Get the first worksheet
	Dim workbook = WorkBook.Load("Spreadsheets\\GDP.xlsx")
	Dim worksheet = workbook.GetWorkSheet("GDPByCountry")
	'Create the database connection
	Using countryContext As New CountryContext()
		'Iterate through all the cells
		For i = 2 To 213
			'Get the range from A-B
			Dim range = worksheet($"A{i}:B{i}").ToList()
			'Create a Country entity to be saved to the database
			Dim country As New Country With {
				.Name = CStr(range(0).Value),
				.GDP = CDec(CDbl(range(1).Value))
			}
			'Add the entity
			Await countryContext.Countries.AddAsync(country)
		Next i
		'Commit changes to the database
		Await countryContext.SaveChangesAsync()
	End Using
End Function
VB   C#

样本 ExcelToDB

5.从应用程序接口下载数据到电子表格

下面的调用使用 RestClient.Net.它下载 JSON 并将其转换为 "RestCountry "类型的 "List"。然后就可以轻松地遍历每个国家,并将数据从 REST API 保存到 Excel 电子表格中。

:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-14.cs
var client = new Client(new Uri("https://restcountries.eu/rest/v2/"));
List<RestCountry> countries = await client.GetAsync<List<RestCountry>>();
Dim client As New Client(New Uri("https://restcountries.eu/rest/v2/"))
Dim countries As List(Of RestCountry) = Await client.GetAsync(Of List(Of RestCountry))()
VB   C#

样本 ApiToExcel

这就是 API JSON 数据的样子。

以下代码会遍历所有国家,并在电子表格中设置名称、人口、地区、数字代码和前 3 种语言。

:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-15.cs
for (var i = 2; i < countries.Count; i++)
{
    var country = countries[i];
    //Set the basic values
    workSheet[$"A{i}"].Value = country.name;
    workSheet[$"B{i}"].Value = country.population;
    workSheet[$"G{i}"].Value = country.region;
    workSheet[$"H{i}"].Value = country.numericCode;
    //Iterate through languages
    for (var x = 0; x < 3; x++)
    {
        if (x > (country.languages.Count - 1)) break;
        var language = country.languages[x];
        //Get the letter for the column
        var columnLetter = GetColumnLetter(4 + x);
        //Set the language name
        workSheet[$"{columnLetter}{i}"].Value = language.name;
    }
}
For i = 2 To countries.Count - 1
	Dim country = countries(i)
	'Set the basic values
	workSheet($"A{i}").Value = country.name
	workSheet($"B{i}").Value = country.population
	workSheet($"G{i}").Value = country.region
	workSheet($"H{i}").Value = country.numericCode
	'Iterate through languages
	For x = 0 To 2
		If x > (country.languages.Count - 1) Then
			Exit For
		End If
		Dim language = country.languages(x)
		'Get the letter for the column
		Dim columnLetter = GetColumnLetter(4 + x)
		'Set the language name
		workSheet($"{columnLetter}{i}").Value = language.name
	Next x
Next i
VB   C#

对象参考和资源

您还可以找到 IronXL 类文档 在对象参考中具有重要价值。

此外,还有其他教程可帮助您了解 "IronXL.Excel "的其他方面,包括 创建, 打开、编写、编辑、保存和导出 XLS、XLSX 和 CSV 文件,而无需使用 Excel Interop

摘要

IronXL.Excel 是一个单独的 .NET 软件库,用于读取各种电子表格格式。它不需要 微软Excel 安装,而不依赖于 Interop。

如果您发现.NET 库在修改 Excel 文件时非常有用,您可能也有兴趣了解一下 Google Sheets API 客户端库 它允许你修改 Google Sheets。


教程快速访问

将本教程下载为 C&num;源代码

本教程的完整免费 C# for Excel 源代码以压缩的 Visual Studio 2017 项目文件形式提供下载。

下载

在 GitHub 上探索此教程

GitHub 上有该项目的 C&num 和 VB.NET 源代码。

使用此代码,只需几分钟就能轻松上手并运行。该项目保存为 Microsoft Visual Studio 2017 项目,但兼容任何 .NET IDE。

如何用 C&num 读取 Excel 文件;在 GitHub 上

查看应用程序接口参考

探索 IronXL 的 API 参考,其中概述了 IronXL 的所有功能、命名空间、类、方法字段和枚举的详细信息。

查看应用程序接口参考
.NET 解决方案总监,负责Microsoft Excel文档输入输出

克里斯蒂安·费因德莱

软件开发团队负责人

Christian为健康行业开发软件,并领导一个团队。Christian具有多年的系统集成经验。IronXL允许Christian从不同来源导入和处理数据,以自动化重复性任务并验证来自第三方来源的输入数据。