与其他组件比较

IronXL与Epplus的比较

发布 2022年三月23日
分享:

本文将探讨 IronXL 和 EPPlus 软件的异同。

对于大多数组织而言,Microsoft Excel 已被证明是一个非常有用的工具。Excel 文件(如数据库)在单元格中包含数据,因此很容易管理需要存储的数据。

Excel 还使用.xls 和.xlsx 文件格式。C# 语言会使 Excel 文件的管理变得困难。不过,IronXL 和 EPPlus 软件可以让您更轻松地处理这些流程。

使用该软件时不需要 Microsoft Office。

请注意,您可以使用 C# 阅读和创建 Excel 文件,而无需安装 Microsoft Office。今天,我们将介绍一些易于实现的不同选项。

什么是 EPPlus 软件?

EPPlus 是一个基于 NuGet 的 .NET Framework/.NET Core 库,用于处理 Office Open XML 电子表格。第 5 版支持 .NET Framework 3.5 和 .NET Core 2.0。EPPlus 不依赖任何其他库,如 Microsoft Excel。

EPPlus 的 API 可让您处理 Office Excel 文档。EPPlus 是一个 .NET 库,可读写 Office OpenXML 格式的 Excel 文件。该库可通过 NuGet 打包获得。

该库是以程序员为中心创建的。我们的目标一直是让熟悉 Excel 或其他电子表格库的开发人员能够快速掌握 API。或者,就像有人说的那样,"IntelliSense 你的胜利之路!"

EPPlus 安装

要从 Visual Studio 安装 EPPlus,请转到 "视图">"其他窗口">"软件包管理器控制台",然后键入以下命令:

安装软件包 EPPlus

如果您想使用 .NET CLI,请从高架命令提示符或 PowerShell 提示符运行以下命令:

PM> dotnet add package EPPlus.

EPPlus 是一个 dotnet 软件包,您可以将其添加到您的项目中。

什么是 IronXL?

IronXL 是一个简单的 C# 和 VB Excel API,能让你在 .NET 中以闪电般的速度读取、编辑和创建 Excel 电子表格文件。它无需安装 Microsoft Office 或 Excel Interop。该库还可用于处理 Excel 文件。

IronXL 支持 .NET Core、.NET Framework、Xamarin、Mobile、Linux、macOS 和 Azure。

电子表格有多种不同的数据读写方式。

使用 NuGet 软件包添加 IronXL

我们可以通过三种方式之一将 IronXL 软件包添加到您的账户,您可以选择最适合您的方式。

  • 使用软件包管理器控制台安装 IronXL

使用以下命令在项目中打开软件包管理器控制台:

要访问软件包管理器控制台,请转到工具 => NuGet 软件包管理器 => 软件包管理器控制台。

这将带你进入软件包管理器控制台。然后,在软件包管理器终端上键入以下命令:

PM > Install-Package IronXL.Excel `PM > 安装软件包 IronXL.Excel

  • 使用 NuGet 软件包管理器安装 IronXL

这是一种不同的 NuGet 包管理器安装方法。如果之前已使用前一种方法完成安装,则无需使用这种方法。

要访问 NuGet 包管理器,请转到工具 > NuGet 包管理器 => 从下拉菜单中选择管理解决方案的 NuGet 包。

这将启动 NuGet 解决方案;选择 "浏览 "并查找 IronXL。

在搜索栏中输入 Excel:

点击 "安装 "按钮后,IronXL 将为您安装。安装完 IronXL 后,您就可以进入表单并开始开发了。

使用 IronXL 创建 Excel 文件

用 IronXL 制作 Excel 工作簿再简单不过了! 只有一行代码! 是的,没错:

WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);
WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);
Dim workbook As WorkBook = WorkBook.Create(ExcelFileFormat.XLSX)
VB   C#

IronXL 可以创建 XLS 格式的文件 (较早的 Excel 文件版本) 和 XLSX (当前和更新的 Excel 文件版本) 格式。

  • 设置默认工作表

设置默认工作表更简单:

var sheet = workbook.CreateWorkSheet("2020年预算");

在上述代码片段中,工作表以 "Sheet "表示,你可以用它来设置单元格值,并做几乎所有 Excel 能做的事情。您还可以将 Excel 文档编码为只读文件,并执行删除操作。您还可以像 Excel 一样链接工作表。

如果你不清楚工作簿和工作表之间的区别,请听我慢慢道来。

工作表包含在工作簿中。这意味着你可以在一个工作簿中放置任意多的工作表。我将在后面的文章中介绍如何做到这一点。行和列组成工作表。行和列的交叉点称为单元格,您将在 Excel 中与单元格进行交互。

使用 Epplus Software AB 创建 Excel 文件

EPPlus 可用于创建 Excel 文件并执行各种操作,如创建数据透视表、数据透视区域,甚至条件格式化和更改字体。下面是将普通 DataTable 转换为 XLSX Excel 文件并发送给用户下载的全部源代码,不再赘述:

public ActionResult ConvertToXLSX()
{
    byte [] fileData = null;

    // replace the GetDataTable() method with your DBMS-fetching code.
    using (DataTable dt = GetDataTable())
    {
        // create an empty spreadsheet
        using (var p = new ExcelPackage())
        {
            // add a worksheet to the spreadsheet
            ExcelWorksheet ws = p.Workbook.Worksheets.Add(dt.TableName);

            // Initialize rows and cols counter: note that they are 1-based!
            var row = 1;
            var col = 1;

            // Create the column names on the first line.
            // In this sample we'll just use the DataTable colum names
            row = 1;
            col = 0;
            foreach (DataColumn dc in dt.Columns)
            {
                col++;
                ws.SetValue(row, col, dc.ColumnName);
            }

            // Insert the DataTable rows to the XLS file
            foreach (DataRow r in dt.Rows)
            {
                row++;
                col = 0;
                foreach (DataColumn dc in dt.Columns)
                {
                    col++;
                    ws.SetValue(row, col, r [dc].ToString());
                }

                // alternate light-gray color for uneven rows (3, 5, 7, 9)...
                if (row % 2 != 0)
                {
                    ws.Row(row).Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
                    ws.Row(row).Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.LightGray);
                }
            }

            // output the XLSX file
            using (var ms = new MemoryStream())
            {
                p.SaveAs(ms);
                ms.Seek(0, SeekOrigin.Begin);
                fileData = ms.ToArray();
            }
        }
    }

    string fileName = "ConvertedFile.xlsx";
    string contentType = System.Web.MimeMapping.GetMimeMapping(fileName);
    Response.AppendHeader("Content-Disposition", String.Format("attachment;filename={0}", fileName));
    return File(fileData, contentType);
}
public ActionResult ConvertToXLSX()
{
    byte [] fileData = null;

    // replace the GetDataTable() method with your DBMS-fetching code.
    using (DataTable dt = GetDataTable())
    {
        // create an empty spreadsheet
        using (var p = new ExcelPackage())
        {
            // add a worksheet to the spreadsheet
            ExcelWorksheet ws = p.Workbook.Worksheets.Add(dt.TableName);

            // Initialize rows and cols counter: note that they are 1-based!
            var row = 1;
            var col = 1;

            // Create the column names on the first line.
            // In this sample we'll just use the DataTable colum names
            row = 1;
            col = 0;
            foreach (DataColumn dc in dt.Columns)
            {
                col++;
                ws.SetValue(row, col, dc.ColumnName);
            }

            // Insert the DataTable rows to the XLS file
            foreach (DataRow r in dt.Rows)
            {
                row++;
                col = 0;
                foreach (DataColumn dc in dt.Columns)
                {
                    col++;
                    ws.SetValue(row, col, r [dc].ToString());
                }

                // alternate light-gray color for uneven rows (3, 5, 7, 9)...
                if (row % 2 != 0)
                {
                    ws.Row(row).Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
                    ws.Row(row).Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.LightGray);
                }
            }

            // output the XLSX file
            using (var ms = new MemoryStream())
            {
                p.SaveAs(ms);
                ms.Seek(0, SeekOrigin.Begin);
                fileData = ms.ToArray();
            }
        }
    }

    string fileName = "ConvertedFile.xlsx";
    string contentType = System.Web.MimeMapping.GetMimeMapping(fileName);
    Response.AppendHeader("Content-Disposition", String.Format("attachment;filename={0}", fileName));
    return File(fileData, contentType);
}
Public Function ConvertToXLSX() As ActionResult
	Dim fileData() As Byte = Nothing

	' replace the GetDataTable() method with your DBMS-fetching code.
	Using dt As DataTable = GetDataTable()
		' create an empty spreadsheet
		Using p = New ExcelPackage()
			' add a worksheet to the spreadsheet
			Dim ws As ExcelWorksheet = p.Workbook.Worksheets.Add(dt.TableName)

			' Initialize rows and cols counter: note that they are 1-based!
			Dim row = 1
			Dim col = 1

			' Create the column names on the first line.
			' In this sample we'll just use the DataTable colum names
			row = 1
			col = 0
			For Each dc As DataColumn In dt.Columns
				col += 1
				ws.SetValue(row, col, dc.ColumnName)
			Next dc

			' Insert the DataTable rows to the XLS file
			For Each r As DataRow In dt.Rows
				row += 1
				col = 0
				For Each dc As DataColumn In dt.Columns
					col += 1
					ws.SetValue(row, col, r (dc).ToString())
				Next dc

				' alternate light-gray color for uneven rows (3, 5, 7, 9)...
				If row Mod 2 <> 0 Then
					ws.Row(row).Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid
					ws.Row(row).Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.LightGray)
				End If
			Next r

			' output the XLSX file
			Using ms = New MemoryStream()
				p.SaveAs(ms)
				ms.Seek(0, SeekOrigin.Begin)
				fileData = ms.ToArray()
			End Using
		End Using
	End Using

	Dim fileName As String = "ConvertedFile.xlsx"
	Dim contentType As String = System.Web.MimeMapping.GetMimeMapping(fileName)
	Response.AppendHeader("Content-Disposition", String.Format("attachment;filename={0}", fileName))
	Return File(fileData, contentType)
End Function
VB   C#

如您所见,这是一个 ActionResult 方法,可用于任何 ASP.NET MVC 控制器;如果您没有使用 ASP.NET MVC,只需复制该方法的内容并粘贴到需要的地方即可 (经典 ASP.NET、控制台应用程序、Windows 窗体等).

代码不言自明,注释足以帮助您理解各种处理过程。但首先,请简要回顾一下我们在这里要做什么:

  • 使用自定义数据提供程序方法,我们获得了一个 DataTable 对象。
  • 我们创建一个 ExcelPackage 对象,它是 EPPlus 处理 XLSX 文件的主要容器。
  • 我们在 ExcelPackage 中添加一个 ExcelWorksheet,它将是输入数据的工作表。
  • 为了创建标题行,我们遍历 DataTable 列,将其添加到工作表的第一行。
  • 我们遍历 DataTable 行,逐行添加到工作表中 (从第 2 行开始) 以便每个 DataTable 行对应一个工作表行。
  • 数据表到 ExcelPackage 的转换完成后,我们将创建一个 MemoryStream 来存储 ExcelPackage 二进制数据,然后将其转换为字节数组。

  • 我们创建 HTML 答案,并将 XLSX 文件发送给用户,同时附上一个 Content-Disposition 附件,使浏览器自动下载该文件。

在这种情况下,IronXL 胜出的原因是其创建过程非常简单--只需一行代码即可完成;这有助于节省时间和调试,而 EPPlus 提供的代码行数太多,既枯燥又难以调试。

EPPlus Software AB 如何编写 Excel 文件

EPPlus 支持 Excel 文件的处理。它是一个可读写 Excel 文件的 .net 库。

  • 读取 Excel 文件

为此,您需要先安装 EPPlus 软件包:进入 "工具"->"NuGet 软件包管理器"->"管理此解决方案的 NuGet"->"安装 EPPlus" ->"Install EPPlus" ->"Install EPPlus" ->"Install EPPlus" ->"Install EPPlus" ->"Install EP 在 "浏览 "选项卡中搜索 "EPPlus",然后安装 NuGet 软件包。

安装软件包后,您可以在控制台应用程序 "Program.cs "中使用下面的代码。

using OfficeOpenXml;
using System;
using System.IO;

namespace ReadExcelInCsharp
{
    class Program
    {
        static void Main(string [] args)
        {
            //provide file path
            FileInfo existingFile = new FileInfo(@"D:\sample_XLSX.xlsx");
            //use EPPlus
            using (ExcelPackage package = new ExcelPackage(existingFile))
            {
                //get the first worksheet in the workbook
                ExcelWorksheet worksheet = package.Workbook.Worksheets [1];
                int colCount = worksheet.Dimension.End.Column;  //get Column Count
                int rowCount = worksheet.Dimension.End.Row;     //get row count
                for (int row = 1; row <= rowCount; row++)
                {
                    for (int col = 1; col <= colCount; col++)
                    {
                        //Print data, based on row and columns position
                        Console.WriteLine(" Row:" + row + " column:" + col + " Value:" + worksheet.Cells [row, col].Value?.ToString().Trim());
                    }
                }
            }
        }
    }
}
using OfficeOpenXml;
using System;
using System.IO;

namespace ReadExcelInCsharp
{
    class Program
    {
        static void Main(string [] args)
        {
            //provide file path
            FileInfo existingFile = new FileInfo(@"D:\sample_XLSX.xlsx");
            //use EPPlus
            using (ExcelPackage package = new ExcelPackage(existingFile))
            {
                //get the first worksheet in the workbook
                ExcelWorksheet worksheet = package.Workbook.Worksheets [1];
                int colCount = worksheet.Dimension.End.Column;  //get Column Count
                int rowCount = worksheet.Dimension.End.Row;     //get row count
                for (int row = 1; row <= rowCount; row++)
                {
                    for (int col = 1; col <= colCount; col++)
                    {
                        //Print data, based on row and columns position
                        Console.WriteLine(" Row:" + row + " column:" + col + " Value:" + worksheet.Cells [row, col].Value?.ToString().Trim());
                    }
                }
            }
        }
    }
}
Imports OfficeOpenXml
Imports System
Imports System.IO

Namespace ReadExcelInCsharp
	Friend Class Program
		Shared Sub Main(ByVal args() As String)
			'provide file path
			Dim existingFile As New FileInfo("D:\sample_XLSX.xlsx")
			'use EPPlus
			Using package As New ExcelPackage(existingFile)
				'get the first worksheet in the workbook
				Dim worksheet As ExcelWorksheet = package.Workbook.Worksheets (1)
				Dim colCount As Integer = worksheet.Dimension.End.Column 'get Column Count
				Dim rowCount As Integer = worksheet.Dimension.End.Row 'get row count
				For row As Integer = 1 To rowCount
					For col As Integer = 1 To colCount
						'Print data, based on row and columns position
						Console.WriteLine(" Row:" & row & " column:" & col & " Value:" & worksheet.Cells (row, col).Value?.ToString().Trim())
					Next col
				Next row
			End Using
		End Sub
	End Class
End Namespace
VB   C#

下面是一个控制台应用程序输出的示例,其中包含一个 excel 文件样本 (.xlsx) 我们正在使用的下面是使用 EPPlus 在 C# 中读取的 xlsx 文件。

使用 "单元格 "属性可以访问以下从多个来源加载数据的方法 (范围):

  • 使用 LoadFromText 和 LoadFromTextAsync 读取 CSV 文本文件并将数据加载到工作表的某个范围。
  • LoadFromDataReaderAsync 和 LoadFromDataReader - 将数据字段从数据阅读器加载到范围中。
  • LoadFromDataTable - 将数据表中的数据加载到范围中。它可以从各种来源导入数据,包括 XML (举例说明) 和数据库。
  • LoadFromCollection - 以反射方式将数据从 IEnumerable 加载到一个范围内。
  • 带属性的 LoadFromCollection - 将数据从一个 IEnumerable 加载到一个范围或表格中。可通过属性指定样式、数字格式、公式和其他属性。
  • LoadFromDictionaries - 从 ExpandoObject/动态对象的 IEnumerable 中加载数据 (通过其 IDictionarystring、object> 接口) 到一个范围内。这对导入 JSON 数据非常有用,其中包含一个示例。

  • LoadFromArray - 从对象的 IEnumerable 中加载数据 [] 的范围,每个对象数组对应工作表中的一行。

使用这些方法时,您可以选择提供一个参数来生成 Excel 表格。示例项目 Sample-.NET Framework 或 Sample-.NET Framework 中的示例 4 和示例 5 包含更多示例。

  • 编写 Excel 文件

接下来,让我们看看能否将数据导出到新的 Excel 文件。

下面是一些我们希望保存为 Excel 文档的示例数据/对象。

List<UserDetails> persons = new List<UserDetails>()
            {
                new UserDetails() {ID="9999", Name="ABCD", City ="City1", Country="USA"},
                new UserDetails() {ID="8888", Name="PQRS", City ="City2", Country="INDIA"},
                new UserDetails() {ID="7777", Name="XYZZ", City ="City3", Country="CHINA"},
                new UserDetails() {ID="6666", Name="LMNO", City ="City4", Country="UK"},
           };
List<UserDetails> persons = new List<UserDetails>()
            {
                new UserDetails() {ID="9999", Name="ABCD", City ="City1", Country="USA"},
                new UserDetails() {ID="8888", Name="PQRS", City ="City2", Country="INDIA"},
                new UserDetails() {ID="7777", Name="XYZZ", City ="City3", Country="CHINA"},
                new UserDetails() {ID="6666", Name="LMNO", City ="City4", Country="UK"},
           };
Dim persons As New List(Of UserDetails)() From {
	New UserDetails() With {
		.ID="9999",
		.Name="ABCD",
		.City ="City1",
		.Country="USA"
	},
	New UserDetails() With {
		.ID="8888",
		.Name="PQRS",
		.City ="City2",
		.Country="INDIA"
	},
	New UserDetails() With {
		.ID="7777",
		.Name="XYZZ",
		.City ="City3",
		.Country="CHINA"
	},
	New UserDetails() With {
		.ID="6666",
		.Name="LMNO",
		.City ="City4",
		.Country="UK"
	}
}
VB   C#

要创建一个包含基本信息的新 Excel 文件,我们必须使用 ExcelPackage 类。将数据写入文件并生成新的 Excel 电子表格只需几行代码。请注意下面的一行代码,它可以神奇地将数据表加载到 Excel 表中。

为了简单起见,我在同一个项目文件夹中生成一个新的电子表格文件 (Excel 文件将在项目的 "bin "文件夹中生成).源代码如下:

private static void WriteToExcel(string path)
        {
            //Let use below test data for writing it to excel
            List<UserDetails> persons = new List<UserDetails>()
            {
                new UserDetails() {ID="9999", Name="ABCD", City ="City1", Country="USA"},
                new UserDetails() {ID="8888", Name="PQRS", City ="City2", Country="INDIA"},
                new UserDetails() {ID="7777", Name="XYZZ", City ="City3", Country="CHINA"},
                new UserDetails() {ID="6666", Name="LMNO", City ="City4", Country="UK"},
           };

            // let's convert our object data to Datatable for a simplified logic.
            // Datatable is the easiest way to deal with complex datatypes for easy reading and formatting. 
            DataTable table = (DataTable)JsonConvert.DeserializeObject(JsonConvert.SerializeObject(persons), (typeof(DataTable)));
            FileInfo filePath = new FileInfo(path);
            using (var excelPack = new ExcelPackage(filePath))
            {
                var ws = excelPack.Workbook.Worksheets.Add("WriteTest");
                ws.Cells.LoadFromDataTable(table, true, OfficeOpenXml.Table.TableStyles.Light8);
                excelPack.Save();
            }
        }
private static void WriteToExcel(string path)
        {
            //Let use below test data for writing it to excel
            List<UserDetails> persons = new List<UserDetails>()
            {
                new UserDetails() {ID="9999", Name="ABCD", City ="City1", Country="USA"},
                new UserDetails() {ID="8888", Name="PQRS", City ="City2", Country="INDIA"},
                new UserDetails() {ID="7777", Name="XYZZ", City ="City3", Country="CHINA"},
                new UserDetails() {ID="6666", Name="LMNO", City ="City4", Country="UK"},
           };

            // let's convert our object data to Datatable for a simplified logic.
            // Datatable is the easiest way to deal with complex datatypes for easy reading and formatting. 
            DataTable table = (DataTable)JsonConvert.DeserializeObject(JsonConvert.SerializeObject(persons), (typeof(DataTable)));
            FileInfo filePath = new FileInfo(path);
            using (var excelPack = new ExcelPackage(filePath))
            {
                var ws = excelPack.Workbook.Worksheets.Add("WriteTest");
                ws.Cells.LoadFromDataTable(table, true, OfficeOpenXml.Table.TableStyles.Light8);
                excelPack.Save();
            }
        }
Private Shared Sub WriteToExcel(ByVal path As String)
			'Let use below test data for writing it to excel
			Dim persons As New List(Of UserDetails)() From {
				New UserDetails() With {
					.ID="9999",
					.Name="ABCD",
					.City ="City1",
					.Country="USA"
				},
				New UserDetails() With {
					.ID="8888",
					.Name="PQRS",
					.City ="City2",
					.Country="INDIA"
				},
				New UserDetails() With {
					.ID="7777",
					.Name="XYZZ",
					.City ="City3",
					.Country="CHINA"
				},
				New UserDetails() With {
					.ID="6666",
					.Name="LMNO",
					.City ="City4",
					.Country="UK"
				}
			}

			' let's convert our object data to Datatable for a simplified logic.
			' Datatable is the easiest way to deal with complex datatypes for easy reading and formatting. 
			Dim table As DataTable = CType(JsonConvert.DeserializeObject(JsonConvert.SerializeObject(persons), (GetType(DataTable))), DataTable)
			Dim filePath As New FileInfo(path)
			Using excelPack = New ExcelPackage(filePath)
				Dim ws = excelPack.Workbook.Worksheets.Add("WriteTest")
				ws.Cells.LoadFromDataTable(table, True, OfficeOpenXml.Table.TableStyles.Light8)
				excelPack.Save()
			End Using
End Sub
VB   C#

在调用上述 API 进行数据验证后,将创建一个新的 Excel 文件,并将上述自定义对象转换到相应的 Excel 列和行中,以显示以下值。

上述即用型 API 可在 .NET Core 控制台、测试项目或 ASP.NET Core 应用程序中使用,其逻辑可根据需要进行更改。

可以使用 "单元格 "属性访问这些技术 (范围):

  • ToText 和 ToTextAsync - 从范围创建 CSV 字符串。
  • 使用 SaveToText 和 SaveToTextAsync 将范围写入 CSV 文件。
  • 使用 ToDataTable 方法将数据从范围导出到系统。数据表
  • GetValueT> - 显示带有数据类型选项的值。

  • Value - 返回或设置范围的值。

GetValue 和 SetValue 方法也可直接用于工作表对象。 (这比在靶场上读取/写入的效果要好一些):

  • GetValueT> - 获取单个单元格的值,并可指定数据类型。
  • SetValue - 更改单个单元格的值。

由于单元格属性实现了 IEnumerable 接口,因此 Linq 可用来查询工作表中的数据。

利用 IronXL 打开和写入 Office Open XML 格式 XLSX

IronXL 是一个.NET 库,可让 C# 开发人员快速、轻松地处理 Excel、数据透视表和其他电子表格文件。

不需要 Office Interop。在 Core 或 Azure 上安装 Microsoft Office 没有特别的依赖性或必要性。

IronXL 是适用于 .NET core 和 .NET framework 的著名 C# 和 VB.NET xl 电子表格库。

  • 读取 Excel 文件
  • 要加载的工作表

Excel 工作表由 WorkBook 类表示。我们利用 WorkBook 在 C# 中打开一个 Excel 文件,其中甚至包含数据透视表。加载 Excel 文件并选择其位置 (.xlsx).

/**
Load WorkBook
anchor-load-a-workbook
**/
var workbook = WorkBook.Load(@"Spreadsheets\\GDP.xlsx");
/**
Load WorkBook
anchor-load-a-workbook
**/
var workbook = WorkBook.Load(@"Spreadsheets\\GDP.xlsx");
'''
'''Load WorkBook
'''anchor-load-a-workbook
'''*
Dim workbook = WorkBook.Load("Spreadsheets\\GDP.xlsx")
VB   C#

在许多工作簿中都可以找到工作表对象。这些是 Excel 文档的工作表。如果工作表中包含工作表,请使用 WorkBook 名称查找它们。获取工作表

var worksheet = workbook.GetWorkSheet("GDPByCountry");
var worksheet = workbook.GetWorkSheet("GDPByCountry");
Dim worksheet = workbook.GetWorkSheet("GDPByCountry")
VB   C#
  • **自制作业本。

使用工作表类型构建新的工作簿,在内存中生成新的工作簿。

/**
Create WorkBook
anchor-create-a-workbook
**/
var workbook = new WorkBook(ExcelFileFormat.XLSX);
/**
Create WorkBook
anchor-create-a-workbook
**/
var workbook = new WorkBook(ExcelFileFormat.XLSX);
'''
'''Create WorkBook
'''anchor-create-a-workbook
'''*
Dim workbook As New WorkBook(ExcelFileFormat.XLSX)
VB   C#

对于老式 Microsoft Excel 电子表格,请使用 ExcelFileFormat.XLS (95 及更早).

如果还没有工作表,请制作一个

每个 "工作簿 "中可以有多个工作表。工作表 "是单个数据表,而 "工作簿 "是工作表的集合。在 Excel 中,包含两个工作表的工作簿就是这样的。

工作簿是您可以创建的新工作表的名称。

var worksheet = workbook.CreateWorkSheet("Countries");
var worksheet = workbook.CreateWorkSheet("Countries");
Dim worksheet = workbook.CreateWorkSheet("Countries")
VB   C#

将工作表名称传递给 CreateWorkSheet。

获取单元格区域

单元格 "对象的二维集合由 "单元格区域 "类表示。它表示 Excel 单元格的特定范围。使用工作表对象上的字符串索引器,可以获取单元格区域。

var range = worksheet ["D2:D101"];
var range = worksheet ["D2:D101"];
Dim range = worksheet ("D2:D101")
VB   C#

参数文本可以是单元格的坐标 (例如,"A1) 或从左到右、从上到下的单元格范围 (例如:"B2:E5").也可以从工作表中调用 GetRange。

  • 在范围内编辑单元格值

可以通过多种方式读取或编辑范围内单元格的值。如果已知计数,则使用 For 循环。您还可以在这里对单元格进行样式设置。

/**
Edit Cell Values in Range
anchor-edit-cell-values-within-a-range
**/
//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);
}
/**
Edit Cell Values in Range
anchor-edit-cell-values-within-a-range
**/
//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);
}
'''
'''Edit Cell Values in Range
'''anchor-edit-cell-values-within-a-range
'''*
'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#

验证电子表格中的数据

要验证数据表,请使用 IronXL。DataValidation 示例使用 libphonenumber-CSharp 验证电话号码,使用传统的 C# API 验证电子邮件地址和日期。

/**
Validate Spreadsheet Data
anchor-validate-spreadsheet-data
**/
//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);
}
/**
Validate Spreadsheet Data
anchor-validate-spreadsheet-data
**/
//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);
}
'''
'''Validate Spreadsheet Data
'''anchor-validate-spreadsheet-data
'''*
'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#

上面的代码在电子表格的行中循环,以列表的形式抓取单元格。每个验证方法都会验证单元格的值,如果值不正确,则返回错误信息。

该代码创建一个新工作表,指定页眉,并生成错误信息结果,以便保存错误数据日志。

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

使用实体框架导出数据

使用 IronXL 将 Excel 电子表格转换为数据库,或将数据导出到数据库。ExcelToDB 示例可读取包含各国国内生产总值的电子表格,并将其导出到 SQLite。

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

应安装 SQLite Entity Framework NuGet 软件包。

您可以使用 EntityFramework 构建一个可以向数据库导出数据的模型对象。

public class Country
{
    [Key]
    public Guid Key { get; set; }
    public string Name { get; set; }
    public decimal GDP { get; set; }
}
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 的等效版本 ().

/**
Export Data using Entity Framework
anchor-export-data-using-entity-framework
**/
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);
    }

}
/**
Export Data using Entity Framework
anchor-export-data-using-entity-framework
**/
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);
    }

}
'''
'''Export Data using Entity Framework
'''anchor-export-data-using-entity-framework
'''*
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 将数据保存到数据库。

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

将公式纳入电子表格

公式属性可用于设置单元格的公式。

//Iterate through all rows with a value
for (var y = 2; y < i; y++)
{
    //Get the C cell
    var cell = sheet [$"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
for (var y = 2; y < i; y++)
{
    //Get the C cell
    var cell = sheet [$"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 = sheet ($"C{y}").First()

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

C 栏中的代码遍历每个州,并计算出总百分比。

可将 API 中的数据下载到电子表格中

在下面的调用中使用 RestClient.Net 进行 REST 调用。它下载 JSON 并将其转换为 RestCountry 类型的 "列表"。然后,可以通过遍历每个国家,轻松地将 REST API 中的数据保存到 Excel 文件中。

/**
Data API to Spreadsheet
anchor-download-data-from-an-api-to-spreadsheet
**/
var client = new Client(new Uri("https://restcountries.eu/rest/v2/"));
List<RestCountry> countries = await client.GetAsync<List<RestCountry>>();
/**
Data API to Spreadsheet
anchor-download-data-from-an-api-to-spreadsheet
**/
var client = new Client(new Uri("https://restcountries.eu/rest/v2/"));
List<RestCountry> countries = await client.GetAsync<List<RestCountry>>();
'''
'''Data API to Spreadsheet
'''anchor-download-data-from-an-api-to-spreadsheet
'''*
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#

来自应用程序接口的 JSON 数据如下所示:

下面的代码循环显示国家,并在电子表格中填入名称、人口、地区、数字代码和前 3 种语言。

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 (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 打开 Excel 文件

启动 Excel 文件后,添加读取第 1 个工作表中第 1 个单元格的前几行并打印。

static void Main(string [] args)
{
    var workbook = IronXL.WorkBook.Load($@"{Directory.GetCurrentDirectory()}\Files\HelloWorld.xlsx");
    var sheet = workbook.WorkSheets.First();
    var cell = sheet ["A1"].StringValue;
    Console.WriteLine(cell);
}
static void Main(string [] args)
{
    var workbook = IronXL.WorkBook.Load($@"{Directory.GetCurrentDirectory()}\Files\HelloWorld.xlsx");
    var sheet = workbook.WorkSheets.First();
    var cell = sheet ["A1"].StringValue;
    Console.WriteLine(cell);
}
Shared Sub Main(ByVal args() As String)
	Dim workbook = IronXL.WorkBook.Load($"{Directory.GetCurrentDirectory()}\Files\HelloWorld.xlsx")
	Dim sheet = workbook.WorkSheets.First()
	Dim cell = sheet ("A1").StringValue
	Console.WriteLine(cell)
End Sub
VB   C#

使用 IronXL 创建一个新的 Excel 文件。

/**
Create Excel File
anchor-create-a-new-excel-file
**/
static void Main(string [] args)
{
    var newXLFile = WorkBook.Create(ExcelFileFormat.XLSX);
    newXLFile.Metadata.Title = "IronXL New File";
    var newWorkSheet = newXLFile.CreateWorkSheet("1stWorkSheet");
    newWorkSheet ["A1"].Value = "Hello World";
    newWorkSheet ["A2"].Style.BottomBorder.SetColor("#ff6600");
    newWorkSheet ["A2"].Style.BottomBorder.Type = IronXL.Styles.BorderType.Dashed;
}
/**
Create Excel File
anchor-create-a-new-excel-file
**/
static void Main(string [] args)
{
    var newXLFile = WorkBook.Create(ExcelFileFormat.XLSX);
    newXLFile.Metadata.Title = "IronXL New File";
    var newWorkSheet = newXLFile.CreateWorkSheet("1stWorkSheet");
    newWorkSheet ["A1"].Value = "Hello World";
    newWorkSheet ["A2"].Style.BottomBorder.SetColor("#ff6600");
    newWorkSheet ["A2"].Style.BottomBorder.Type = IronXL.Styles.BorderType.Dashed;
}
'''
'''Create Excel File
'''anchor-create-a-new-excel-file
'''*
Shared Sub Main(ByVal args() As String)
	Dim newXLFile = WorkBook.Create(ExcelFileFormat.XLSX)
	newXLFile.Metadata.Title = "IronXL New File"
	Dim newWorkSheet = newXLFile.CreateWorkSheet("1stWorkSheet")
	newWorkSheet ("A1").Value = "Hello World"
	newWorkSheet ("A2").Style.BottomBorder.SetColor("#ff6600")
	newWorkSheet ("A2").Style.BottomBorder.Type = IronXL.Styles.BorderType.Dashed
End Sub
VB   C#

之后,您可以使用各自的代码将其保存为 CSV、JSON 或 XML。

例如,要保存为 XML".xml"

要保存为 XML,请使用 SaveAsXml,如下所示:

newXLFile.SaveAsXml($@"{Directory.GetCurrentDirectory()}\Files\HelloWorldXML.XML");
newXLFile.SaveAsXml($@"{Directory.GetCurrentDirectory()}\Files\HelloWorldXML.XML");
newXLFile.SaveAsXml($"{Directory.GetCurrentDirectory()}\Files\HelloWorldXML.XML")
VB   C#

结果是这样的

<?xml version="1.0" standalone="yes"?>
<_x0031_stWorkSheet>
  <_x0031_stWorkSheet>
    <Column1 xsi:type="xs:string" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">Hello World</Column1>
  </_x0031_stWorkSheet>
  <_x0031_stWorkSheet>
    <Column1 xsi:type="xs:string" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" />
  </_x0031_stWorkSheet>
</_x0031_stWorkSheet>
XML

使用 IronXL 比使用 EPPlus 更容易读取 Excel 文件。IronXL 的代码更简短,包含了访问工作簿中所有列、行和单元格所需的全部内容,而使用 EPPlus 则需要一行特定的代码才能读取列和行。

在操作 Excel 文档方面,IronXL 更加智能。它能让你在任何时候创建更多工作表,还能从多个工作表和工作簿中读取数据,而 EPPlus 一次只能处理一个工作表。有了 IronXL,你还可以用 Excel 工作簿中的数据填充数据库。

EPPlus 和 IronXL 许可和定价

EPPlus 许可证模式和价格

EPPlus 可在两种许可模式下使用,一种是非商业许可模式,另一种是 Polyform 提供的商业许可模式。

商业许可证

这些许可证有永久和订购两种形式,期限从一个月到两年不等。

对于所有许可类别,在许可期限内都包括通过支持中心提供的支持和通过 NuGet 进行的升级。

EPPlus 要求每个开发人员拥有一个许可证。许可证只发给一个人,不能共享。作为一般准则,制作或需要调试直接使用 EPPlus 的代码的任何人都应获得商业许可证。

如果您在内部将 EPPlus 作为一项服务提供 (例如,通过应用程序接口公开其功能), 贵公司必须购买涵盖内部用户数量的套餐 (开发者) 谁将使用该服务。

订阅

您可以通过订阅始终使用最新版本,但只要您使用 EPPlus 进行开发,就必须拥有有效的许可证。在许可期结束时,许可证会自动开具发票,并在付款后自动更新。您可以在许可期结束时取消订阅,并随时开始新的订阅。订阅只能在互联网上购买。

EPPlus 可用于商业环境。每家公司可向一名开发人员发放许可证,部署地点不限。每年可购买的许可证数量可增加或减少,每年结束时可暂停或取消许可证。

可选择 32 天的试用期。

定价: 每年 299 美元起。

您可以随用随付

单个组织内每位开发人员的价格,部署地点不限,可使用 Stripe 开具发票。每月可用的许可证数量可增加或减少,许可证可在每月月底暂停或取消。

定价: 每月 29 美元起。

永久许可证

永久许可证允许您在一定时间内更新到新版本并获得支持。然后,您可以继续使用在此期间发布的版本开发软件,而无需更新许可证。

在同一公司内,每个开发人员的价格不受限制。无限期使用支持/升级期限内发布的所有 EPPlus 版本。

可选择 32 天试用期。

定价: 每年 599 美元起。

套餐

提供永久许可证选项,初始期限为升级和支持。在此期间,您可以继续使用已发布的版本开发软件,而无需更新许可证。

定价: 每年 4295 美元起。

用于 Polyform 的非商业许可证

EPPlus 从第 5 版开始采用 Polyform 非商业许可证,这表明代码是开源的,可用于非商业用途。您可以在其网站上查看更多详细信息。

IronXL 许可模式和价格

永久许可证: 每个许可证只需购买一次,无需更新。

免费支持和产品更新:每个许可证都附带一年的免费产品更新和产品团队支持。可随时购买扩展。可查看扩展。

立即许可证:收到付款后,立即发送注册许可证密钥。

如果您对 IronXL for .NET 许可有任何疑问,请联系我们的 Iron Software 许可专家。

所有许可证都是永久性的,适用于开发、暂存和生产。

Lite - 允许企业中的单个软件开发人员在一个地方使用 Iron 软件。Iron 软件可用于单个网络应用程序、内联网应用程序或桌面软件程序。许可证不可转让,也不能在组织或代理/客户关系之外共享。本许可类型与所有其他许可类型一样,明确排除本协议未明确授予的所有权利,包括 OEM 再分发和在未购买额外保险的情况下将 Iron 软件作为 SaaS 使用。

定价: 每年 489 美元起。

专业许可证 - 允许组织内预定数量的软件开发人员在一个地点使用 Iron 软件,最多不超过 10 人。您可以在任意数量的网站、内联网应用程序或桌面软件应用程序中使用 Iron 软件。许可证不可转让,也不能在组织或代理/客户关系之外共享。本许可类型与所有其他许可类型一样,明确排除本协议未明确授予的所有权利,包括 OEM 再分发和在未购买额外保险的情况下将 Iron 软件作为 SaaS 使用。

定价: 每年 976 美元起。

无限制许可 - 允许组织内数量不限的软件开发人员在数量不限的地点使用 Iron 软件。您可以在任意数量的网站、内联网应用程序或桌面软件应用程序中使用 Iron 软件。许可证不可转让,也不能在组织或代理/客户关系之外共享。本许可类型与所有其他许可类型一样,明确排除本协议未明确授予的所有权利,包括 OEM 再分发和在未购买额外保险的情况下将 Iron 软件作为 SaaS 使用。

Royalty-Free Redistribution - 允许您将 Iron 软件作为多种不同的打包商业产品的一部分进行分发。 (无需支付版税) 根据基本许可证涵盖的项目数量。根据基本许可证涵盖的项目数量,允许在 SaaS 软件服务中部署 Iron 软件。

定价: 每年 2939 美元起。

结论

总之,IronXL 比 EPPlus 更为实用,因为它让您可以根据需要灵活地在 Excel 表中进行导航,代码行数更少,导出的机会更多,包括 XML、HTML 和 JSON。IronXL 还允许您将工作簿数据整合到数据库中。此外,它还有一个直观的系统,可在每次编辑文档时重新计算公式,并提供带有工作表的直观范围设置。 ["A1:B10"] 语法工作表功能包括与 Excel 配合使用的公式,每次编辑工作表都会重新计算。单元格数据格式包括多种文本、数字、公式、日期、货币、百分比、科学记数法和时间。其自定义格式有不同的排序方法,如范围、列和行。其单元格样式包括各种字体、大小、背景图案、边框和对齐方式。

< 前一页
IronXL 与 Aspose Cells 的对比
下一步 >
IronXL与Microsoft Office Interop Excel的比较

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

免费NuGet下载 总下载量: 988,189 查看许可证 >