# A Guide to Reading and Writing Excel Files in C#
Leer y crear archivos de Excel (XLS, XLSX y CSV) en C# y otros lenguajes .NET es fácil usando la biblioteca de software IronXL de Iron Software.
IronXL no requiere que se instale Excel Interop en su servidor. 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, Maui y Xamarin
## Instalar IronXL
Firstly install IronXL, using our NuGet package or by <a class="js-modal-open" href="/csharp/excel/packages/IronXL.zip" data-modal-id="trial-license-after-download">downloading the DLL</a>. IronXL classes can be found in the `IronXL` namespace.
La forma más fácil de instalar IronXL es utilizando el Administrador de Paquetes NuGet para Visual-Studio:
El nombre del paquete es **IronXL.Excel**.
```shell
:ProductInstall
```
<a class="js-modal-open" href="https://www.nuget.org/packages/IronXL.Excel/" target="_blank" data-modal-id="trial-license-after-download">https://www.nuget.org/packages/IronXL.Excel/</a>
## Leyendo un documento de Excel
Con IronXL, extraer datos de un archivo de Excel se puede hacer en solo unas pocas líneas de código.
```csharp
:path=/static-assets/excel/content-code-examples/get-started/get-started-1.cs
```
## Creación de nuevos documentos de Excel
IronXL ofrece una interfaz rápida y sencilla para generar documentos de Excel usando C# o VB.NET.
```csharp
:path=/static-assets/excel/content-code-examples/get-started/get-started-2.cs
```
## Exportar como CSV, XLS, XLSX, JSON o XML
IronXL también le permite guardar o exportar datos a una variedad de formatos de hoja de cálculo estructurados populares.
```csharp
:path=/static-assets/excel/content-code-examples/get-started/get-started-3.cs
```
## Dar estilo a celdas y rangos
Puede aplicar formato a celdas y rangos de Excel usando el objeto IronXL.Range.Style.
```csharp
:path=/static-assets/excel/content-code-examples/get-started/get-started-4.cs
```
## Rangos de clasificación
Con IronXL, puede ordenar un rango de celdas de Excel fácilmente usando el objeto Range.
```csharp
:path=/static-assets/excel/content-code-examples/get-started/get-started-5.cs
```
## Edición de fórmulas
Modificar una fórmula de Excel es tan simple como asignar un valor que comience con un signo igual (=). La fórmula se calculará instantáneamente.
```csharp
:path=/static-assets/excel/content-code-examples/get-started/get-started-6.cs
```
## ¿Por qué elegir IronXL?
IronXL ofrece una API amigable para desarrolladores para leer y escribir documentos de Excel en .NET.
Funciona sin requerir que Microsoft Excel o Excel Interop estén instalados en el servidor, haciendo el manejo de archivos Excel rápido, ligero y sin complicaciones.
## Avanzando
Para explorar más características y capacidades, le recomendamos revisar la [Referencia de API .NET](/csharp/excel/object-reference/) formateada de manera similar a la documentación de MSDN.
Con IronXL, extraer datos de un archivo de Excel se puede hacer en solo unas pocas líneas de código.
using IronXL;// Supported spreadsheet formats for reading include: XLSX, XLS, CSV and TSVWorkBook workBook = WorkBook.Load("data.xlsx");WorkSheet workSheet = workBook.WorkSheets.First();// Select cells easily in Excel notation and return the calculated value, date, text or formulaint 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);}
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);
}
ImportsIronXL' Supported spreadsheet formats for reading include: XLSX, XLS, CSV and TSVPrivate workBook AsWorkBook = WorkBook.Load("data.xlsx")Private workSheet AsWorkSheet = workBook.WorkSheets.First()' Select cells easily in Excel notation and return the calculated value, date, text or formulaPrivate cellValue AsInteger = 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
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
Creación de nuevos documentos de Excel
IronXL ofrece una interfaz rápida y sencilla para generar documentos de Excel usando C# o VB.NET.
using IronXL;// Create new Excel WorkBook document.WorkBook workBook = WorkBook.Create(ExcelFileFormat.XLSX);workBook.Metadata.Author = "IronXL";// Add a blank WorkSheetWorkSheet workSheet = workBook.CreateWorkSheet("main_sheet");// Add data and styles to the new worksheetworkSheet["A1"].Value = "Hello World";workSheet["A2"].Style.BottomBorder.SetColor("#ff6600");workSheet["A2"].Style.BottomBorder.Type = IronXL.Styles.BorderType.Double;// Save the excel fileworkBook.SaveAs("NewExcelFile.xlsx");
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");
ImportsIronXL' Create new Excel WorkBook document.Private workBook AsWorkBook = WorkBook.Create(ExcelFileFormat.XLSX)workBook.Metadata.Author = "IronXL"' Add a blank WorkSheetDim workSheet AsWorkSheet = workBook.CreateWorkSheet("main_sheet")' Add data and styles to the new worksheetworkSheet("A1").Value = "Hello World"workSheet("A2").Style.BottomBorder.SetColor("#ff6600")workSheet("A2").Style.BottomBorder.Type = IronXL.Styles.BorderType.Double' Save the excel fileworkBook.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")
Exportar como CSV, XLS, XLSX, JSON o XML
IronXL también le permite guardar o exportar datos a una variedad de formatos de hoja de cálculo estructurados populares.
// Export to many formats with fluent savingworkSheet.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");
' Export to many formats with fluent savingworkSheet.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")
Dar estilo a celdas y rangos
Puede aplicar formato a celdas y rangos de Excel usando el objeto IronXL.Range.Style.
// Set cell's value and stylesworkSheet["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;
' Set cell's value and stylesworkSheet("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
Rangos de clasificación
Con IronXL, puede ordenar un rango de celdas de Excel fácilmente usando el objeto Range.
using IronXL;using Range = IronXL.Range;WorkBook workBook = WorkBook.Load("test.xls");WorkSheet workSheet = workBook.WorkSheets.First();// This is how we get range from Excel worksheetRange range = workSheet["A2:A8"];// Sort the range in the sheetrange.SortAscending();workBook.Save();
using IronXL;
using Range = IronXL.Range;
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();
ImportsIronXLDim workBook AsWorkBook = WorkBook.Load("test.xls")Dim workSheet AsWorkSheet = workBook.WorkSheets.First()' This is how we get range from Excel worksheetDim range AsRange = workSheet("A2:A8")' Sort the range in the sheetrange.SortAscending()workBook.Save()
Imports IronXL
Dim workBook As WorkBook = WorkBook.Load("test.xls")
Dim workSheet As WorkSheet = workBook.WorkSheets.First()
' This is how we get range from Excel worksheet
Dim range As Range = workSheet("A2:A8")
' Sort the range in the sheet
range.SortAscending()
workBook.Save()
Edición de fórmulas
Modificar una fórmula de Excel es tan simple como asignar un valor que comience con un signo igual (=). La fórmula se calculará instantáneamente.
// Set a formulaworkSheet["A1"].Value = "=SUM(A2:A10)";// Get the calculated valuedecimal sum = workSheet["A1"].DecimalValue;
// Set a formula
workSheet["A1"].Value = "=SUM(A2:A10)";
// Get the calculated value
decimal sum = workSheet["A1"].DecimalValue;
' Set a formulaworkSheet("A1").Value = "=SUM(A2:A10)"' Get the calculated valueDim sum AsDecimal = workSheet("A1").DecimalValue
' Set a formula
workSheet("A1").Value = "=SUM(A2:A10)"
' Get the calculated value
Dim sum As Decimal = workSheet("A1").DecimalValue
¿Por qué elegir IronXL?
IronXL ofrece una API amigable para desarrolladores para leer y escribir documentos de Excel en .NET.
Funciona sin requerir que Microsoft Excel o Excel Interop estén instalados en el servidor, haciendo el manejo de archivos Excel rápido, ligero y sin complicaciones.
Avanzando
Para explorar más características y capacidades, le recomendamos revisar la Referencia de API .NET formateada de manera similar a la documentación de MSDN.
Curtis Chau tiene una licenciatura en Ciencias de la Computación (Carleton University) y se especializa en el desarrollo front-end con experiencia en Node.js, TypeScript, JavaScript y React. Apasionado por crear interfaces de usuario intuitivas y estéticamente agradables, disfruta trabajando con frameworks modernos y creando manuales bien estructurados y visualmente atractivos.