Archivos de hoja de cálculo Excel en aplicaciones C# y VB.NET

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

Lectura y creación de Excel (XLS, XLSX y CSV) en C# y todos los demás lenguajes .NET es fácil utilizando la biblioteca de software IronXL de Iron Software.

IronXL no requiere que Excel esté instalado en su servidor o Interop. IronXL proporciona una API más rápida e intuitiva que Microsoft.Office.Interop.Excel.

IronXL funciona en las siguientes plataformas:

  • .NET Framework 4.6.2 y superior para Windows y Azure
  • .NET Core 2 y superior para Windows, Linux, MacOS y Azure
  • .NET 5, .NET 6, .NET 7, .NET 8, Mono, Mobile y Xamarin

Instalar IronXL

En primer lugar instale IronXL, utilizando nuestro paquete NuGet o mediante descargar la DLL. Las clases IronXL se encuentran en la sección IronXL espacio de nombres.

La forma más sencilla de instalar IronXL es utilizando el gestor de paquetes NuGet para Visual-Studio: El nombre del paquete es IronXL.Excel.

Install-Package IronXL.Excel

https://www.nuget.org/packages/ironxl.excel/

Lectura de un documento Excel

La lectura de datos de un archivo Excel con IronXL requiere unas pocas líneas de código.

:path=/static-assets/excel/content-code-examples/get-started/get-started-1.cs
using IronXL;

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

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

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

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

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

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

Creación de nuevos documentos Excel

Para crear documentos Excel en C# o VB.NET; IronXL ofrece una interfaz sencilla y rápida.

:path=/static-assets/excel/content-code-examples/get-started/get-started-2.cs
using IronXL;

// Create new Excel WorkBook document.
WorkBook workBook = WorkBook.Create(ExcelFileFormat.XLSX);
workBook.Metadata.Author = "IronXL";

// Add a blank WorkSheet
WorkSheet workSheet = workBook.CreateWorkSheet("main_sheet");

// Add data and styles to the new worksheet
workSheet["A1"].Value = "Hello World";
workSheet["A2"].Style.BottomBorder.SetColor("#ff6600");
workSheet["A2"].Style.BottomBorder.Type = IronXL.Styles.BorderType.Double;

// Save the excel file
workBook.SaveAs("NewExcelFile.xlsx");
Imports IronXL

' Create new Excel WorkBook document.
Private workBook As WorkBook = WorkBook.Create(ExcelFileFormat.XLSX)
workBook.Metadata.Author = "IronXL"

' Add a blank WorkSheet
Dim workSheet As WorkSheet = workBook.CreateWorkSheet("main_sheet")

' Add data and styles to the new worksheet
workSheet("A1").Value = "Hello World"
workSheet("A2").Style.BottomBorder.SetColor("#ff6600")
workSheet("A2").Style.BottomBorder.Type = IronXL.Styles.BorderType.Double

' Save the excel file
workBook.SaveAs("NewExcelFile.xlsx")
VB   C#

Exportación como CSV, XLS, XLSX, JSON o XML

También podemos guardar o exportar como muchos formatos de archivo de hojas de cálculo estructuradas comunes.

:path=/static-assets/excel/content-code-examples/get-started/get-started-3.cs
// Export to many formats with fluent saving
workSheet.SaveAs("NewExcelFile.xls");
workSheet.SaveAs("NewExcelFile.xlsx");
workSheet.SaveAsCsv("NewExcelFile.csv");
workSheet.SaveAsJson("NewExcelFile.json");
workSheet.SaveAsXml("NewExcelFile.xml");
' Export to many formats with fluent saving
workSheet.SaveAs("NewExcelFile.xls")
workSheet.SaveAs("NewExcelFile.xlsx")
workSheet.SaveAsCsv("NewExcelFile.csv")
workSheet.SaveAsJson("NewExcelFile.json")
workSheet.SaveAsXml("NewExcelFile.xml")
VB   C#

Estilización de celdas y rangos

Las celdas y rangos de Excel pueden ser estilizados utilizando el objeto IronXL.Range.Style.

:path=/static-assets/excel/content-code-examples/get-started/get-started-4.cs
// Set cell's value and styles
workSheet["A1"].Value = "Hello World";
workSheet["A2"].Style.BottomBorder.SetColor("#ff6600");
workSheet["A2"].Style.BottomBorder.Type = IronXL.Styles.BorderType.Double;
' Set cell's value and styles
workSheet("A1").Value = "Hello World"
workSheet("A2").Style.BottomBorder.SetColor("#ff6600")
workSheet("A2").Style.BottomBorder.Type = IronXL.Styles.BorderType.Double
VB   C#

Rangos de clasificación

Usando un IronXL podemos ordenar un rango de Celdas Excel usando Range.

:path=/static-assets/excel/content-code-examples/get-started/get-started-5.cs
using IronXL;

WorkBook workBook = WorkBook.Load("test.xls");
WorkSheet workSheet = workBook.WorkSheets.First();

// This is how we get range from Excel worksheet
Range range = workSheet["A2:A8"];

// Sort the range in the sheet
range.SortAscending();
workBook.Save();
Imports IronXL

Private workBook As WorkBook = WorkBook.Load("test.xls")
Private workSheet As WorkSheet = workBook.WorkSheets.First()

' This is how we get range from Excel worksheet
Private range As Range = workSheet("A2:A8")

' Sort the range in the sheet
range.SortAscending()
workBook.Save()
VB   C#

Edición de fórmulas

Editar una fórmula de Excel es tan fácil como asignar un valor con un signo igual = al principio. La fórmula se calculará en directo.

:path=/static-assets/excel/content-code-examples/get-started/get-started-6.cs
// Set a formula
workSheet["A1"].Value = "=SUM(A2:A10)";

// Get the calculated value
decimal sum = workSheet["A1"].DecimalValue;
' Set a formula
workSheet("A1").Value = "=SUM(A2:A10)"

' Get the calculated value
Dim sum As Decimal = workSheet("A1").DecimalValue
VB   C#

¿Por qué elegir IronXL?

IronXL ofrece una API sencilla para que los desarrolladores lean y escriban documentos Excel para .NET.

IronXL no requiere la instalación de Microsoft Excel en su servidor o Excel Interop para acceder a los documentos de Excel. Esto hace que trabajar con archivos Excel en .NET, sea una tarea muy rápida y sencilla.

Avanzar

Para sacar el máximo partido a IronXL, le recomendamos que lea la documentación de la aplicación Referencia API .NET en formato MSDN.