Una comparación entre IronXL y Epplus
En este artículo, examinamos las similitudes y diferencias entre el software IronXL y EPPlus.
Para la mayoría de las organizaciones, Microsoft Excel ha demostrado ser una herramienta extremadamente útil. Archivos Excel, como bases de datos, contienen datos en celdas, lo que simplemente facilita la gestión de los datos que necesitan ser almacenados.
Los formatos de archivo .xls y .xlsx también son usados por Excel. El lenguaje C# puede dificultar la gestión de archivos Excel. Sin embargo, los software IronXL y EPPlus facilitan el manejo de estos procesos.
No se requiere Microsoft Office al usar este software.
Por favor, tenga en cuenta que puede leer y crear archivos Excel en C# sin tener que instalar Microsoft Office. Hoy, veremos algunas opciones diferentes que son fáciles de implementar.
Cómo leer un archivo de Excel en C# usando EPPlus
- Descargue e instale la biblioteca C# EPPlus
- Utilice la clase C# EPPlus
ExcelPackagepara leer archivos de Excel - Leer y modificar datos según la posición de fila y columna en la hoja
- Rellene una hoja de Excel rápidamente con el método
LoadFromDataTable - Exportar archivo Excel con EPPlus C#
¿Qué es el software EPPlus?
EPPlus es una biblioteca basada en NuGet para .NET Framework/.NET Core para gestionar hojas de cálculo Office Open XML. La versión 5 incluye soporte para .NET Framework 3.5 y .NET Core 2.0. EPPlus no depende de otras bibliotecas, como Microsoft Excel.
EPPlus tiene una API que permite trabajar con documentos Excel de Office. EPPlus es una biblioteca .NET que lee y escribe archivos Excel en formato OpenXML de Office. Esta biblioteca está disponible como un paquete de NuGet.
La biblioteca fue creada con la programación en mente. El objetivo siempre ha sido que un desarrollador familiarizado con Excel u otra biblioteca de hojas de cálculo pueda aprender rápidamente a usar la API. Alternativamente, como alguien dijo: "¡Utiliza IntelliSense para ganar!"
Instalación de EPPlus
Para instalar EPPlus desde Visual Studio, vaya a Ver > Otras Ventanas > Consola del Administrador de Paquetes y escriba el siguiente comando:
Install-Package EPPlus
Si prefieres utilizar la CLI de .NET, ejecuta el siguiente comando desde un símbolo del sistema elevado o un PowerShell:
dotnet add package EPPlus
EPPlus es un paquete de dotnet que puedes añadir a tu proyecto.
¿Qué es IronXL?
IronXL es una sencilla API de Excel para C# y VB que le permite leer, editar y crear archivos de hoja de cálculo Excel en .NET a una velocidad vertiginosa. No es necesario instalar Microsoft Office o siquiera Excel Interop. Esta biblioteca también se puede utilizar para trabajar con archivos Excel.
.NET Core, .NET Framework, Xamarin, Mobile, Linux, macOS y Azure son compatibles con IronXL.
Hay varias formas de leer y escribir datos hacia y desde su hoja de cálculo.
Agregar IronXL mediante el paquete NuGet
Podemos agregar el paquete IronXL a su cuenta de una de tres formas, para que pueda elegir la que mejor le funcione.
- Usando la Consola del Administrador de Paquetes para instalar IronXL
Usa el siguiente comando para abrir la Consola del Administrador de Paquetes en tu Proyecto:
Para acceder a la Consola del Administrador de Paquetes, ve a Herramientas => Administrador de Paquetes de NuGet => Consola del Administrador de Paquetes.

Esto le llevará a la Consola del Administrador de Paquetes. Luego, en la terminal del Administrador de Paquetes, escriba el siguiente comando:
Install-Package IronXL.Excel

- Usando el Administrador de Paquetes NuGet para instalar IronXL
Este es un enfoque diferente para obtener el Administrador de Paquetes NuGet instalado. No necesitará utilizar este enfoque si ya ha completado la instalación utilizando el método anterior.
Para acceder al Administrador de Paquetes NuGet, vaya a Herramientas > Administrador de Paquetes NuGet => Seleccione Administrar Paquetes NuGet para la Solución del menú desplegable.
Esto lanzará la Solución NuGet; seleccione "Explorar" y busque IronXL.
En la barra de búsqueda, escriba Excel:

IronXL se instalará para usted cuando haga clic en el botón "Instalar". Después de instalar IronXL puede ir a su formulario y comenzar a desarrollarlo.
Creación de un archivo Excel con IronXL
¡Crear un nuevo Libro de Excel con IronXL no podría ser más fácil! ¡Es solo una línea de código! Sí, esto es cierto:
// Create a new Excel workbook in XLSX format
WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);// Create a new Excel workbook in XLSX format
WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);' Create a new Excel workbook in XLSX format
Dim workbook As WorkBook = WorkBook.Create(ExcelFileFormat.XLSX)IronXL puede crear archivos en los formatos XLS (la versión anterior de archivo Excel) y XLSX (versión actual y más reciente de archivo Excel).
- Establecer hoja de trabajo predeterminada
Es aún más fácil configurar una hoja de cálculo predeterminada:
// Create a worksheet named "2020 Budget" in the workbook
var sheet = workbook.CreateWorkSheet("2020 Budget");// Create a worksheet named "2020 Budget" in the workbook
var sheet = workbook.CreateWorkSheet("2020 Budget");' Create a worksheet named "2020 Budget" in the workbook
Dim sheet = workbook.CreateWorkSheet("2020 Budget")La hoja de cálculo está representada por sheet en el fragmento de código anterior, y puede usarlo para establecer valores de celda y hacer prácticamente todo lo que Excel puede hacer. También puede codificar su documento Excel a un archivo de solo lectura y realizar operaciones de eliminación. También puede vincular sus hojas de trabajo, tal como lo hace Excel.
Permíteme clarificar la diferencia entre un libro y una hoja de cálculo en caso de que no estés seguro.
Las hojas de trabajo están contenidas en un libro. Esto significa que puede poner tantas hojas de trabajo dentro de un libro como desee. Explicaré cómo hacer esto en un artículo posterior. Las hojas de cálculo constan de filas y columnas. La intersección de una fila y una columna se conoce como celda, y es con lo que va a interactuar dentro de Excel.
Creación de un archivo Excel con EPPlus Software AB
EPPlus se puede utilizar para crear archivos Excel y realizar operaciones como crear tablas dinámicas, áreas de pivote e incluso formato condicional y el cambio de fuentes. Sin más preámbulos, aquí está el código fuente completo para convertir un DataTable normal a un archivo Excel XLSX y enviarlo al usuario para su descarga:
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 columns 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 column names
row = 1;
col = 0;
foreach (DataColumn dc in dt.Columns)
{
col++;
ws.SetValue(row, col, dc.ColumnName);
}
// Insert the DataTable rows into 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 columns 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 column names
row = 1;
col = 0;
foreach (DataColumn dc in dt.Columns)
{
col++;
ws.SetValue(row, col, dc.ColumnName);
}
// Insert the DataTable rows into 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 columns 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 column 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 into 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 FunctionComo puede ver, este es un método ActionResult que puede ser utilizado en cualquier controlador ASP.NET MVC; si no está usando ASP.NET MVC, simplemente copie el contenido del método y péguelo donde lo necesite (por ejemplo, ASP.NET clásico, Aplicación de Consola, Formularios de Windows, etc.).
El código es autodocumentado, con bastantes comentarios para ayudarle a entender los diversos procesos de procesamiento. Pero primero, un repaso rápido de lo que estamos haciendo aquí:
- Usando un método de Proveedor de Datos personalizado, obtenemos un objeto
DataTable. - Construimos un objeto
ExcelPackage, que es el contenedor primario de EPPlus para el archivo XLSX. - Agregamos un
ExcelWorksheetalExcelPackage, que será la hoja de trabajo donde se ingresarán los datos. - Para crear nuestra fila de encabezado, iteramos las columnas del
DataTable, agregándolas a la primera fila de nuestra hoja de trabajo. - Iteramos a través de las filas del
DataTable, agregando cada una a nuestra hoja de trabajo fila por fila (comenzando con la fila 2) para que cada fila delDataTablecorresponda a una fila de hoja de trabajo. - Construimos un
MemoryStreampara almacenar los datos binarios delExcelPackagecuando se complete la conversión deDataTableaExcelPackagey luego lo convertimos a un arreglo de bytes. - Creamos la respuesta HTML y enviamos el archivo XLSX al usuario con un adjunto de Content-Disposition, haciendo que el navegador descargue automáticamente el archivo.
IronXL gana en este caso porque el proceso de creación es muy fácil: solo necesita una línea de código y ya está; esto ayuda a ahorrar tiempo y con la depuración, mientras que EPPlus ofrece líneas de código que son tediosas de revisar y difíciles de depurar.
Cómo EPPlus Software AB escribe archivos de Excel
EPPlus admite el trabajo con archivos Excel. Es una biblioteca .net que lee y escribe archivos Excel.
- Leyendo Archivos Excel
Para hacerlo, primero necesita instalar el paquete EPPlus: vaya a "Herramientas"-> "Administrador de paquetes NuGet"-> "Administrar NuGet para esta solución" -> "Instalar EPPlus" -> "Instalar EPPlus" -> "Instalar EPPlus" -> "Instalar EPPlus" -> "Instalar EPPlus" -> Instalar EP. Busque "EPPlus" en la pestaña "Explorar", luego instale el paquete NuGet.

Puede usar el código a continuación en su aplicación de consola "Program.cs" una vez que haya instalado el paquete.
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 NamespaceAquí hay un ejemplo de salida de aplicación de consola con un archivo Excel de ejemplo (.xlsx) con el que estamos trabajando. Aquí hay un archivo xlsx para leer en C# usando EPPlus.

Las siguientes maneras de cargar datos desde múltiples fuentes pueden ser accedidas usando la propiedad "cells" (ExcelRange):
- Leer un archivo de texto CSV y cargar los datos en un rango de una hoja de cálculo con
LoadFromTextyLoadFromTextAsync. - LoadFromDataReaderAsync y
LoadFromDataReader— carga campos de datos desde un DataReader en un rango. - LoadFromDataTable — carga datos desde un
DataTableen un rango. Puede importar datos desde una variedad de fuentes, incluidas XML (se suministra un ejemplo) y bases de datos. - LoadFromCollection — carga de forma reflexiva datos desde un
IEnumerableen un rango. - LoadFromCollection con atributos — carga de forma reflexiva datos desde un
IEnumerableen un rango o tabla. Los estilos, formatos numéricos, fórmulas y otras propiedades se especifican mediante atributos. - LoadFromDictionaries — carga datos desde un
IEnumerablede objetosExpandoObject/dinámicos (a través de su interfazIDictionary<string, object>) en un rango. Esto es útil para importar datos JSON, y se incluye un ejemplo. - LoadFromArrays — carga datos desde un
IEnumerablede objeto[]en un rango, con cada arreglo de objeto correspondiendo a una fila en la hoja de trabajo.
Al usar estos métodos, puede opcionalmente dar un parámetro para generar una tabla Excel. Las muestras 4 y 5 del proyecto de muestra Sample-.NET Framework contienen ejemplos más extensos.
- Escribiendo Archivos Excel
A continuación, veamos si podemos exportar datos a un nuevo archivo Excel.
Aquí hay algunos datos/objetos de muestra que nos gustaría guardar como un documento 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"
}
}Para crear un nuevo archivo Excel con la información esencial, debemos utilizar la clase ExcelPackage. Escribir datos en un archivo y producir una nueva hoja de cálculo Excel requiere solo unas pocas líneas de código. Tenga en cuenta la única línea a continuación que realiza la magia de cargar DataTables en una hoja Excel.

Para simplificar las cosas, estoy generando un nuevo archivo de hoja de cálculo en la misma carpeta del proyecto (el archivo Excel se producirá en la carpeta 'bin' del proyecto). El código fuente está abajo:
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 SubSiguiendo la llamada a la API mencionada anteriormente para la validación de datos, se creará un nuevo archivo Excel con la transformación de objeto personalizado anterior en las columnas y filas de Excel correspondientes, para mostrar el valor a continuación.

La API lista para usar arriba puede ser utilizada en la consola .NET Core, un proyecto de prueba o una aplicación ASP.NET Core, y la lógica puede ser modificada para adaptarse a sus necesidades.
Estas técnicas pueden ser accesadas usando la propiedad "cells" (ExcelRange):
- ToText and ToTextAsync — crea una cadena CSV desde un rango.
- Escribir un rango en un archivo CSV con
SaveToTextySaveToTextAsync. - Exportar datos desde un rango a un System usando el método
ToDataTable*DataTable*. DataTable - Value — devuelve o establece el valor del rango. Los métodos
GetValueySetValuese pueden usar en el objeto hoja de trabajo.
Los métodos GetValue y SetValue también se pueden utilizar directamente en el objeto de la hoja de cálculo. - GetValue — obtiene el valor de una sola celda, con la opción de especificar un tipo de dato.
- SetValue — cambia el valor de una sola celda.
- SetValue — cambia el valor de una celda.
Linq puede ser utilizado para consultar datos de una hoja de cálculo porque la propiedad de la celda implementa la interfaz IEnumerable.
Abrir y escribir en formato Office Open XML XLSX con IronXL
No se requiere la Interop de Office.
No hay dependencias particulares o la necesidad de instalar Microsoft Office en Core o Azure. IronXL es una renombrada biblioteca de hojas de cálculo xl para C# y VB.NET para .NET core y .NET framework.
Hoja de trabajo a ser cargada
- Leyendo Archivos Excel No se requiere Microsoft Office en Core o Azure.
Una hoja Excel se representa mediante la clase WorkBook. Utilizamos WorkBook para abrir un archivo de Excel en C# que contiene incluso tablas dinámicas. Objetos WorkSheet pueden ser encontrados en numerosos WorkBooks.
/**
Load WorkBook
**/
var workbook = WorkBook.Load(@"Spreadsheets\\GDP.xlsx");/**
Load WorkBook
**/
var workbook = WorkBook.Load(@"Spreadsheets\\GDP.xlsx");'''
''' Load WorkBook
''' *
Dim workbook = WorkBook.Load("Spreadsheets\\GDP.xlsx")Estas son las hojas de cálculo del documento Excel. Si la hoja tiene hojas de trabajo, use WorkBook y GetWorkSheet. - Hacer su propio Libro.
var worksheet = workbook.GetWorkSheet("GDPByCountry");var worksheet = workbook.GetWorkSheet("GDPByCountry");Dim worksheet = workbook.GetWorkSheet("GDPByCountry")Usamos WorkBook para abrir un archivo Excel en C# que incluya tablas dinámicas.
Para hojas de cálculo de Microsoft Excel vintage, use ExcelFileFormat.XLS (95 y anteriores).
/**
Create WorkBook
**/
var workbook = new WorkBook(ExcelFileFormat.XLSX);/**
Create WorkBook
**/
var workbook = new WorkBook(ExcelFileFormat.XLSX);'''
''' Create WorkBook
''' *
Dim workbook As New WorkBook(ExcelFileFormat.XLSX)Haz una Hoja de trabajo si no tienes una ya.
Crear una hoja de trabajo si no tiene una.
En Excel, esta es como se ve un libro con dos hojas de trabajo.


Pase el nombre de la hoja de trabajo a CreateWorkSheet.
var worksheet = workbook.CreateWorkSheet("Countries");var worksheet = workbook.CreateWorkSheet("Countries");Dim worksheet = workbook.CreateWorkSheet("Countries")Obtener el Rango Celular
Una colección bidimensional de "Cell" es la clase "Range".
Denota un rango específico de celdas Excel. Denota un rango específico de celdas de Excel. Con el índice de cadena en un objeto de Hoja de trabajo, puedes obtener rangos.
var range = worksheet["D2:D101"];var range = worksheet["D2:D101"];Dim range = worksheet("D2:D101")GetRange también puede ser llamado desde una Hoja de trabajo. - Dentro de un Rango, Editar Valores de Celdas
- Dentro de un rango, editar valores de celdas
Usa un bucle For si se conoce la cuenta. También puedes hacer el estilo de celdas desde aquí. Validar Datos en Hojas de cálculo
/**
Edit Cell Values in 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
**/
// 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
''' *
' 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 yPara validar una hoja de datos, utiliza IronXL.
El ejemplo DataValidation valida teléfonos con libphonenumber-CSharp y correos y fechas con APIs de C#. El código anterior recorre las filas de la hoja de cálculo, tomando las celdas como lista. Cada método validado verifica el valor de una celda y devuelve un error si el valor es incorrecto.
/**
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
**/
// 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
''' *
' 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 iEste código crea una nueva hoja, especifica encabezados y produce los resultados del mensaje de error para que se pueda mantener un registro de datos incorrectos.
Usando Entity Framework para Exportar Datos
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")Usando Entity Framework para exportar datos
El ejemplo ExcelToDB lee una hoja de cálculo que contiene el PIB por nación y lo exporta a SQLite. El ejemplo ExcelToDB lee una hoja de cálculo que contiene el PIB por nación y lo exporta a SQLite.
Se deben instalar los paquetes NuGet de Entity Framework de SQLite.


Usa EntityFramework para construir un objeto modelo que exporte datos a una base de datos.
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 ClassProduzca un CountryContext, luego itere a través del rango para crear cada entrada antes de guardar los datos en la base de datos con SaveChangesAsync.
/**
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
**/
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
''' *
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 ClassIncorpora una Fórmula a una Hoja de cálculo
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 FunctionLa propiedad Formula se puede utilizar para establecer la fórmula de una celda.
La propiedad Formula puede ser utilizada para establecer la fórmula de una celda.
// 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
LoopLos datos de una API pueden descargarse a una hoja de cálculo
Los datos de una API pueden ser descargados a una hoja de cálculo
Usa la propiedad Formula para establecer la fórmula de una celda. Los datos JSON de la API se ven así:
/**
Data 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
**/
var client = new Client(new Uri("https://restcountries.eu/rest/v2/"));
List<RestCountry> countries = await client.GetAsync<List<RestCountry>>();'''
''' Data 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))()RestClient.Net se usa para realizar una llamada REST.

Abrir archivos Excel con IronXL
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 iDespués de iniciar el archivo Excel, agregue las primeras líneas que leen la primera celda en la primera hoja y la imprimen.
Usando IronXL, cree un nuevo archivo Excel.
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 SubAbre archivos de Excel con IronXL.
/**
Create 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
**/
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
''' *
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 SubPor ejemplo, para Guardar en XML .xml
Para guardar en XML use SaveAsXml:
Para guardar en XML utiliza SaveAsXml de la siguiente manera:
newXLFile.SaveAsXml($@"{Directory.GetCurrentDirectory()}\Files\HelloWorldXML.XML");newXLFile.SaveAsXml($@"{Directory.GetCurrentDirectory()}\Files\HelloWorldXML.XML");newXLFile.SaveAsXml($"{Directory.GetCurrentDirectory()}\Files\HelloWorldXML.XML")Leer Excel es más fácil con IronXL que con EPPlus.
<?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 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>IronXL tiene más códigos abreviados para acceder a columnas, filas y celdas en un libro, mientras EPPlus requiere líneas específicas para leer. IronXL es más inteligente a la hora de manipular documentos Excel.
IronXL permite crear más hojas y leer datos de múltiples hojas y libros, mientras EPPlus trata una hoja a la vez. También puede llenar una base de datos desde Excel. ## EPPlus y IronXL Licencias y Precios
Licencias y precios de EPPlus e IronXL
Modelo y precio de la licencia EPPlus
Licencias Comerciales
Licencias comerciales disponibles en formatos perpetuos y por suscripción, de un mes a dos años.
Para todas las categorías de licencias, el soporte a través del centro de soporte y las actualizaciones a través de NuGet están incluidas durante la duración de la licencia.
EPPlus requiere una licencia por desarrollador.
Las licencias son individuales y no se comparten. Como regla general, quien produzca o depure código con EPPlus debe tener licencia comercial. Si ofrece EPPlus internamente (por ejemplo, a través de una API), su empresa debe adquirir suscripción para los desarrolladores que usarán el servicio.
Suscripciones
Siempre puede usar la última versión con suscripción, pero necesita licencia válida para el desarrollo.
Al final del periodo de licencia, la licencia se factura automáticamente y se renueva una vez que se paga el pago. Puede cancelar su suscripción al final del periodo de licencia e iniciar una nueva cuando lo desee. Las suscripciones solo están disponibles para compra en internet. EPPlus se puede utilizar en un entorno comercial.
La licencia es para un desarrollador por empresa, con despliegues ilimitados. El número de licencias anuales puede ajustarse y puede suspenderse o cancelarse al final del año. Se ofrece un periodo de prueba de 32 días como opción.
Pricing: Starts from $299 per year.
Precio por desarrollador para una organización, con despliegues ilimitados y facturación por Stripe.
Precio por desarrollador para una organización, con despliegues ilimitados y facturación por Stripe.
El número de licencias disponibles cada mes puede aumentarse o disminuirse, y la licencia puede suspenderse o cancelarse al final de cada mes. Licencia Perpetua
Licencia Perpetua
Licencia perpetua
Dentro de la misma empresa, precio por desarrollador con sitios de despliegue ilimitados.
Uso indefinido de todas las versiones de EPPlus lanzadas durante el período de soporte/actualizaciones. Paquetes
Pricing: Starts from $299 per year.
Paquetes
Packages
Luego puede continuar desarrollando software usando las versiones lanzadas durante este período sin necesidad de renovar su licencia. Licencia No Comercial para Polyform
Licencia No Comercial para Polyform
Licencia no comercial para Polyform
Puede ver más detalles en su sitio web. ### Modelo de Licencia y Precio de IronXL
Modelo y precio de la licencia IronXL
Licenciamiento perpetuo: cada licencia se compra una vez y no requiere renovación.
Licencias Inmediatas: las claves de licencia registradas se envían tan pronto como se recibe el pago. Es posible comprar extensiones en cualquier momento. Se pueden ver las extensiones.
Contacte a nuestros especialistas de licencias si tiene preguntas sobre IronXL para .NET.
Lite - Permite a un solo desarrollador de software en una organización utilizar el software Iron en un solo lugar.
Todas las licencias son perpetuas y se aplican a desarrollo, staging y producción.
Lite - Permite a un único desarrollador de software en una organización utilizar el software de Iron en un solo lugar. Iron Software se puede utilizar en una sola aplicación web, aplicación de intranet o programa de software de escritorio. Licencia Profesional - Permite a un número definido de desarrolladores usar el software Iron en un solo lugar, hasta diez.
Licencia Profesional - Permite a un número definido de desarrolladores usar el software Iron en un solo lugar, hasta diez.
Licencia Ilimitada - Permite a un número ilimitado de desarrolladores usar el software Iron en múltiples lugares. Iron Software se puede utilizar en tantos sitios web, aplicaciones de intranet o aplicaciones de software de escritorio como desees. Las licencias no son transferibles y no se pueden compartir fuera de una organización o relación de agencia/cliente. Este tipo de licencia, al igual que todos los demás tipos de licencia, excluye expresamente todos los derechos no expresamente otorgados bajo el Acuerdo, incluyendo redistribución OEM y utilización de Iron Software como SaaS sin comprar una cobertura adicional.
Licencia Ilimitada - Permite a un número ilimitado de desarrolladores usar el software Iron en múltiples lugares.
Redistribución Sin Regalías - Le permite distribuir el software Iron como parte de varios productos comerciales empaquetados (sin tener que pagar regalías) basados en el número de proyectos cubiertos por la licencia base. Iron Software se puede utilizar en tantos sitios web, aplicaciones de intranet o aplicaciones de software de escritorio como desees. Las licencias no son transferibles y no se pueden compartir fuera de una organización o relación de agencia/cliente. Este tipo de licencia, al igual que todos los demás tipos de licencia, excluye expresamente todos los derechos no expresamente otorgados bajo el Acuerdo, incluyendo redistribución OEM y utilización de Iron Software como SaaS sin comprar una cobertura adicional.
Redistribución Libre de Regalías - Te permite distribuir el Iron Software como parte de varios productos comerciales empaquetados diferentes (sin tener que pagar regalías) basado en el número de proyectos cubiertos por la licencia base. Precios: Comienza desde $2939 por año.
Precios: Comienza desde $2939 por año.
Conclusión
IronXL también le permite integrar los datos de su libro de trabajo en una base de datos. IronXL permite integrar datos de su libro en una base de datos. Las funciones de hoja incluyen fórmulas que funcionan con Excel y se recalculan cada vez que se edita una hoja. Los formatos de celda incluyen textos, números, fórmulas, fechas, moneda, porcentajes y más, con formatos personalizados por rangos, columnas y filas. Su estilo de celdas incluye una variedad de fuentes, tamaños, patrones de fondo, bordes y alineaciones.
Preguntas Frecuentes
¿Cómo puedo crear archivos Excel sin usar Microsoft Office?
Puedes usar IronXL para crear archivos Excel sin Microsoft Office. IronXL ofrece una API simple para leer, editar y crear hojas de cálculo Excel en C# y VB.NET.
¿Cuáles son las ventajas de usar IronXL sobre EPPlus?
IronXL proporciona una API más intuitiva, soporta múltiples formatos de archivos como XML, HTML y JSON, y permite un avanzado estilado y recalculación de fórmulas. Esto lo hace más práctico y flexible para los desarrolladores en comparación con EPPlus.
¿Es posible manipular datos de Excel y exportarlos a diferentes formatos usando IronXL?
Sí, IronXL permite exportar datos de Excel a varios formatos como XML, HTML y JSON, lo que facilita la integración con bases de datos y otras aplicaciones.
¿Cómo manejas las fórmulas de Excel con IronXL?
IronXL soporta recalculaciones intuitivas de fórmulas, lo que significa que las fórmulas se actualizan automáticamente cada vez que se edita el documento, proporcionando un sistema eficiente para gestionar fórmulas de Excel.
¿Qué opciones de licencia ofrece IronXL?
IronXL ofrece licencias perpetuas para entornos de desarrollo, pruebas y producción con precios a partir de $489 por año para un solo desarrollador. Incluye un año de actualizaciones y soporte gratuito.
¿Se puede usar EPPlus para crear tablas dinámicas y aplicar formato condicional?
Sí, EPPlus admite la creación de tablas dinámicas y la aplicación de formato condicional, aunque en general requiere un código más complejo que IronXL.
¿Cómo admite IronXL el desarrollo multiplataforma?
IronXL soporta una variedad de plataformas, incluyendo .NET Core, .NET Framework, Xamarin, Móvil, Linux, macOS y Azure, lo que lo hace versátil para desarrollo multiplataforma.
¿Requiere IronXL que Microsoft Office esté instalado en el servidor o en la máquina cliente?
No, IronXL no requiere que Microsoft Office esté instalado. Está diseñado para funcionar independientemente de Office, proporcionando capacidades para leer, editar y crear archivos Excel.
¿Cuáles son las características clave de EPPlus para manejar archivos Excel?
EPPlus es conocido por su soporte de Office OpenXML, facilidad de uso para desarrolladores familiarizados con Excel y capacidades como la creación de tablas dinámicas y la aplicación de formato condicional. Está disponible bajo un modelo de doble licencia.
¿Cómo puedo instalar IronXL para mi proyecto .NET?
Puedes instalar IronXL mediante la Consola del Administrador de Paquetes de NuGet con el comando Install-Package IronXL.Excel o utilizando la CLI de .NET con dotnet add package IronXL.Excel.






