Cómo abrir archivos de Excel en C#
IronXL enables C# developers to open, read, and manipulate Excel files without requiring Microsoft Office installation. Simply load workbooks using WorkBook.Load(), access worksheets, and read cell values with intuitive syntax like sheet["A1"].
This tutorial explores using IronXL to open and read Excel files in C# projects, providing junior developers with comprehensive examples and best practices for working with Excel data.
What is IronXL Excel Library?
IronXL is a .NET library that prioritizes ease of use, accuracy, and speed. It helps you open, read, create, and edit Excel files efficiently without requiring MS Office Interop, making it a practical choice for developers seeking to work with Excel in C# without Interop.
IronXL is compatible with all .NET Frameworks along with Linux, macOS, Docker, Azure, and AWS. You can use it to create Console, Web, and Desktop Applications such as Blazor and .NET MAUI for modern Web Apps. It supports different workbook formats like XLS and XLSX files, XSLT and XLSM, CSV, and TSV.
What Are the Key Features of IronXL?
- Open, read, and search data in XLS/XLSX/CSV/TSV formats using LoadSpreadsheets.
- Export Excel Worksheets to multiple formats with Save & Export.
- Encrypt and decrypt files with passwords using secure features.
- Work with Excel sheets as
DataSetandDataTableobjects through DataSet integration. - Excel formulas recalculate automatically, supporting Math Functions.
- Edit spreadsheet data with intuitive range syntax like
WorkSheet["A1:B10"]. - Sort Cell Ranges, Columns, and Rows.
- Style Cells with Font, Background, Border, Alignment, and Number formats.
How to Open an Excel File in C#?
What Do I Need Before Starting?
Para usar IronXL en aplicaciones C#, instala los siguientes componentes en tu computadora local:
- Visual Studio - The official IDE for developing C# .NET applications. Puedes descargar e instalar Visual Studio desde el sitio web de Microsoft. You can also use
JetBrainsReSharper& Rider. For additional setup guidance, refer to the Get Started Overview. - IronXL - The Excel library that helps work with Excel sheets in C#. Debe instalarse en su aplicación C# antes de usarla. You can download it from the NuGet website or from Manage NuGet packages in Visual Studio. También puedes descargar directamente el archivo .NET Excel DLL. For licensing implementation, see Using License Keys.
Which Namespaces Should I Import?
Una vez que Visual Studio e IronXL estén instalados, agrega los espacios de nombres necesarios de IronXL incluyendo la siguiente línea en la parte superior de tu archivo C#:
// Add reference to the IronXL library
using IronXL;
// Add reference to the IronXL library
using IronXL;
' Add reference to the IronXL library
Imports IronXL
For working with specific Excel formats or advanced features, you might also need:
using IronXL.Formatting; // For cell styling
using IronXL.Drawing; // For images and charts
using System.Data; // For DataSet/DataTable operations
using IronXL.Formatting; // For cell styling
using IronXL.Drawing; // For images and charts
using System.Data; // For DataSet/DataTable operations
Imports IronXL.Formatting ' For cell styling
Imports IronXL.Drawing ' For images and charts
Imports System.Data ' For DataSet/DataTable operations
How Do I Load an Existing Excel File?
Los archivos de Excel, también conocidos como libros de trabajo, consisten en múltiples hojas de trabajo, cada una con valores de celda. To open and read an Excel file, load it using the WorkBook class's Load method. The LoadSpreadsheets functionality supports various formats.
// Supported Excel spreadsheet formats for reading include: XLSX, XLS, CSV, and TSV
WorkBook workbook = WorkBook.Load("test.xlsx");
// You can also load from streams for web applications
// using (var stream = File.OpenRead("test.xlsx"))
// {
// WorkBook workbook = WorkBook.Load(stream);
// }
// Supported Excel spreadsheet formats for reading include: XLSX, XLS, CSV, and TSV
WorkBook workbook = WorkBook.Load("test.xlsx");
// You can also load from streams for web applications
// using (var stream = File.OpenRead("test.xlsx"))
// {
// WorkBook workbook = WorkBook.Load(stream);
// }
' Supported Excel spreadsheet formats for reading include: XLSX, XLS, CSV, and TSV
Dim workbook As WorkBook = WorkBook.Load("test.xlsx")
' You can also load from streams for web applications
' Using stream = File.OpenRead("test.xlsx")
' Dim workbook As WorkBook = WorkBook.Load(stream)
' End Using
This initializes the workbook as a WorkBook instance. To open a specific WorkSheet, retrieve it from the WorkSheets collection. The Manage Worksheet guide provides more details on worksheet operations:
// Access the first worksheet in the workbook
WorkSheet sheet = workbook.WorkSheets.First();
// Alternative ways to access worksheets
WorkSheet sheetByIndex = workbook.WorkSheets[0]; // By index
WorkSheet sheetByName = workbook.GetWorkSheet("Sheet1"); // By name
// Access the first worksheet in the workbook
WorkSheet sheet = workbook.WorkSheets.First();
// Alternative ways to access worksheets
WorkSheet sheetByIndex = workbook.WorkSheets[0]; // By index
WorkSheet sheetByName = workbook.GetWorkSheet("Sheet1"); // By name
' Access the first worksheet in the workbook
Dim sheet As WorkSheet = workbook.WorkSheets.First()
' Alternative ways to access worksheets
Dim sheetByIndex As WorkSheet = workbook.WorkSheets(0) ' By index
Dim sheetByName As WorkSheet = workbook.GetWorkSheet("Sheet1") ' By name
Esto accede a la primera hoja en el archivo de Excel, lista para lectura y escritura.
Archivo de Excel
How Do I Read Data from Excel Cells?
Once the Excel file is opened, it's ready for reading data. Leer datos de archivos de Excel en C# usando IronXL es sencillo. You can read cell values by specifying the cell reference using the Select Range functionality.
El siguiente código recupera el valor de una celda:
// Select the cell using Excel notation and retrieve its integer value
int cellValue = sheet["C2"].IntValue;
// You can also retrieve values in different formats
string textValue = sheet["C2"].StringValue;
decimal decimalValue = sheet["C2"].DecimalValue;
DateTime dateValue = sheet["C2"].DateTimeValue;
bool boolValue = sheet["C2"].BoolValue;
// Display the value in the console
Console.WriteLine($"Cell C2 contains: {cellValue}");
// Check if cell is empty before reading
if (!sheet["C2"].IsEmpty)
{
Console.WriteLine($"Cell value: {sheet["C2"].Value}");
}
// Select the cell using Excel notation and retrieve its integer value
int cellValue = sheet["C2"].IntValue;
// You can also retrieve values in different formats
string textValue = sheet["C2"].StringValue;
decimal decimalValue = sheet["C2"].DecimalValue;
DateTime dateValue = sheet["C2"].DateTimeValue;
bool boolValue = sheet["C2"].BoolValue;
// Display the value in the console
Console.WriteLine($"Cell C2 contains: {cellValue}");
// Check if cell is empty before reading
if (!sheet["C2"].IsEmpty)
{
Console.WriteLine($"Cell value: {sheet["C2"].Value}");
}
' Select the cell using Excel notation and retrieve its integer value
Dim cellValue As Integer = sheet("C2").IntValue
' You can also retrieve values in different formats
Dim textValue As String = sheet("C2").StringValue
Dim decimalValue As Decimal = sheet("C2").DecimalValue
Dim dateValue As DateTime = sheet("C2").DateTimeValue
Dim boolValue As Boolean = sheet("C2").BoolValue
' Display the value in the console
Console.WriteLine($"Cell C2 contains: {cellValue}")
' Check if cell is empty before reading
If Not sheet("C2").IsEmpty Then
Console.WriteLine($"Cell value: {sheet("C2").Value}")
End If
El resultado es el siguiente:
Leer Excel
To read data from a range of cells, use a loop to iterate through the specified range. The Select Excel Range example provides more patterns:
// Iterate through a range of cells and display their address and text content
foreach (var cell in sheet["A2:A6"])
{
Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text);
}
// Read an entire column
foreach (var cell in sheet.GetColumn(0)) // Column A
{
if (!cell.IsEmpty)
{
Console.WriteLine($"Column A value: {cell.Text}");
}
}
// Read an entire row
foreach (var cell in sheet.GetRow(1)) // Row 2
{
Console.WriteLine($"Row 2 value: {cell.Text}");
}
// Iterate through a range of cells and display their address and text content
foreach (var cell in sheet["A2:A6"])
{
Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text);
}
// Read an entire column
foreach (var cell in sheet.GetColumn(0)) // Column A
{
if (!cell.IsEmpty)
{
Console.WriteLine($"Column A value: {cell.Text}");
}
}
// Read an entire row
foreach (var cell in sheet.GetRow(1)) // Row 2
{
Console.WriteLine($"Row 2 value: {cell.Text}");
}
' Iterate through a range of cells and display their address and text content
For Each cell In sheet("A2:A6")
Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text)
Next
' Read an entire column
For Each cell In sheet.GetColumn(0) ' Column A
If Not cell.IsEmpty Then
Console.WriteLine($"Column A value: {cell.Text}")
End If
Next
' Read an entire row
For Each cell In sheet.GetRow(1) ' Row 2
Console.WriteLine($"Row 2 value: {cell.Text}")
Next
Each value in the cell range A2:A6 is accessed and printed to the console.
Leer rango de celdas
For more detailed reading and writing examples, check the Excel reading tutorial in C#. You can also convert Excel data to DataTables for easier manipulation:
// Convert worksheet to DataTable for easier data manipulation
DataTable dataTable = sheet.ToDataTable(true); // true = first row contains headers
// Access data using DataTable methods
foreach (DataRow row in dataTable.Rows)
{
Console.WriteLine($"Employee: {row["Name"]}, Salary: {row["Salary"]}");
}
// Convert worksheet to DataTable for easier data manipulation
DataTable dataTable = sheet.ToDataTable(true); // true = first row contains headers
// Access data using DataTable methods
foreach (DataRow row in dataTable.Rows)
{
Console.WriteLine($"Employee: {row["Name"]}, Salary: {row["Salary"]}");
}
' Convert worksheet to DataTable for easier data manipulation
Dim dataTable As DataTable = sheet.ToDataTable(True) ' True = first row contains headers
' Access data using DataTable methods
For Each row As DataRow In dataTable.Rows
Console.WriteLine($"Employee: {row("Name")}, Salary: {row("Salary")}")
Next
How Can I Create a New Excel File?
IronXL also facilitates creating new workbooks for data saving and retrieval. The Create Spreadsheets guide provides comprehensive examples.
Puedes crear un nuevo archivo de Excel con una sola línea de código:
// Create a new workbook with the XLSX format
WorkBook workBook = new WorkBook(ExcelFileFormat.XLSX);
// Alternative: Create with XLS format for compatibility
WorkBook xlsWorkBook = new WorkBook(ExcelFileFormat.XLS);
// Set workbook metadata
workBook.Metadata.Title = "Employee Data";
workBook.Metadata.Author = "Your Name";
workBook.Metadata.Keywords = "employees, salary, data";
// Create a new workbook with the XLSX format
WorkBook workBook = new WorkBook(ExcelFileFormat.XLSX);
// Alternative: Create with XLS format for compatibility
WorkBook xlsWorkBook = new WorkBook(ExcelFileFormat.XLS);
// Set workbook metadata
workBook.Metadata.Title = "Employee Data";
workBook.Metadata.Author = "Your Name";
workBook.Metadata.Keywords = "employees, salary, data";
' Create a new workbook with the XLSX format
Dim workBook As New WorkBook(ExcelFileFormat.XLSX)
' Alternative: Create with XLS format for compatibility
Dim xlsWorkBook As New WorkBook(ExcelFileFormat.XLS)
' Set workbook metadata
workBook.Metadata.Title = "Employee Data"
workBook.Metadata.Author = "Your Name"
workBook.Metadata.Keywords = "employees, salary, data"
A continuación, crea una hoja de trabajo y añade datos a ella. For more advanced creation patterns, see Create a new Excel File.
How Do I Add Worksheets to a Workbook?
// Create a worksheet named "GDPByCountry" in the workbook
WorkSheet workSheet = workBook.CreateWorkSheet("GDPByCountry");
// Create multiple worksheets at once
WorkSheet sheet2 = workBook.CreateWorkSheet("PopulationData");
WorkSheet sheet3 = workBook.CreateWorkSheet("Summary");
// Copy an existing worksheet
WorkSheet copiedSheet = workSheet.CopySheet("GDPByCountryCopy");
// Create a worksheet named "GDPByCountry" in the workbook
WorkSheet workSheet = workBook.CreateWorkSheet("GDPByCountry");
// Create multiple worksheets at once
WorkSheet sheet2 = workBook.CreateWorkSheet("PopulationData");
WorkSheet sheet3 = workBook.CreateWorkSheet("Summary");
// Copy an existing worksheet
WorkSheet copiedSheet = workSheet.CopySheet("GDPByCountryCopy");
' Create a worksheet named "GDPByCountry" in the workbook
Dim workSheet As WorkSheet = workBook.CreateWorkSheet("GDPByCountry")
' Create multiple worksheets at once
Dim sheet2 As WorkSheet = workBook.CreateWorkSheet("PopulationData")
Dim sheet3 As WorkSheet = workBook.CreateWorkSheet("Summary")
' Copy an existing worksheet
Dim copiedSheet As WorkSheet = workSheet.CopySheet("GDPByCountryCopy")
Este código añade una hoja de trabajo llamada "GDPByCountry" al libro de trabajo, permitiéndote añadir valores a celdas. Learn more about managing worksheets and copying worksheets.
Para establecer un valor para una celda específica, utiliza el siguiente código:
// Set the value of cell A1 to "Example"
workSheet["A1"].Value = "Example";
// Add different types of data
workSheet["A2"].Value = 12345; // Integer
workSheet["A3"].Value = 99.99m; // Decimal
workSheet["A4"].Value = DateTime.Now; // Date
workSheet["A5"].Value = true; // Boolean
// Add formulas
workSheet["B1"].Formula = "=SUM(A2:A3)";
// Set multiple cells at once using a range
workSheet["C1:C5"].Value = "Bulk Value";
// Save the workbook
workBook.SaveAs("output.xlsx");
// Set the value of cell A1 to "Example"
workSheet["A1"].Value = "Example";
// Add different types of data
workSheet["A2"].Value = 12345; // Integer
workSheet["A3"].Value = 99.99m; // Decimal
workSheet["A4"].Value = DateTime.Now; // Date
workSheet["A5"].Value = true; // Boolean
// Add formulas
workSheet["B1"].Formula = "=SUM(A2:A3)";
// Set multiple cells at once using a range
workSheet["C1:C5"].Value = "Bulk Value";
// Save the workbook
workBook.SaveAs("output.xlsx");
' Set the value of cell A1 to "Example"
workSheet("A1").Value = "Example"
' Add different types of data
workSheet("A2").Value = 12345 ' Integer
workSheet("A3").Value = 99.99D ' Decimal
workSheet("A4").Value = DateTime.Now ' Date
workSheet("A5").Value = True ' Boolean
' Add formulas
workSheet("B1").Formula = "=SUM(A2:A3)"
' Set multiple cells at once using a range
workSheet("C1:C5").Value = "Bulk Value"
' Save the workbook
workBook.SaveAs("output.xlsx")
El resultado final es:
Añadir Valor a la Celda
Working with Different Excel Formats
IronXL supports multiple Excel formats. Here's how to handle different file types:
// Convert between formats
WorkBook workbook = WorkBook.Load("data.csv");
workbook.SaveAs("data.xlsx"); // Convert CSV to XLSX
// Export to different formats
workbook.SaveAsCsv("output.csv", ";"); // CSV with semicolon delimiter
workbook.SaveAsJson("output.json"); // Export as JSON
workbook.SaveAsXml("output.xml"); // Export as XML
// Convert between formats
WorkBook workbook = WorkBook.Load("data.csv");
workbook.SaveAs("data.xlsx"); // Convert CSV to XLSX
// Export to different formats
workbook.SaveAsCsv("output.csv", ";"); // CSV with semicolon delimiter
workbook.SaveAsJson("output.json"); // Export as JSON
workbook.SaveAsXml("output.xml"); // Export as XML
' Convert between formats
Dim workbook As WorkBook = WorkBook.Load("data.csv")
workbook.SaveAs("data.xlsx") ' Convert CSV to XLSX
' Export to different formats
workbook.SaveAsCsv("output.csv", ";") ' CSV with semicolon delimiter
workbook.SaveAsJson("output.json") ' Export as JSON
workbook.SaveAsXml("output.xml") ' Export as XML
Learn more about converting spreadsheet file types and converting XLSX to CSV, JSON, XML.
Manejo de errores y buenas prácticas
When working with Excel files, implement proper error handling:
try
{
WorkBook workbook = WorkBook.Load("test.xlsx");
WorkSheet sheet = workbook.GetWorkSheet("Sheet1");
// Check if sheet exists
if (sheet == null)
{
Console.WriteLine("Worksheet not found!");
return;
}
// Process data
var value = sheet["A1"].Value;
}
catch (Exception ex)
{
Console.WriteLine($"Error reading Excel file: {ex.Message}");
}
try
{
WorkBook workbook = WorkBook.Load("test.xlsx");
WorkSheet sheet = workbook.GetWorkSheet("Sheet1");
// Check if sheet exists
if (sheet == null)
{
Console.WriteLine("Worksheet not found!");
return;
}
// Process data
var value = sheet["A1"].Value;
}
catch (Exception ex)
{
Console.WriteLine($"Error reading Excel file: {ex.Message}");
}
Imports System
Try
Dim workbook As WorkBook = WorkBook.Load("test.xlsx")
Dim sheet As WorkSheet = workbook.GetWorkSheet("Sheet1")
' Check if sheet exists
If sheet Is Nothing Then
Console.WriteLine("Worksheet not found!")
Return
End If
' Process data
Dim value = sheet("A1").Value
Catch ex As Exception
Console.WriteLine($"Error reading Excel file: {ex.Message}")
End Try
For production applications, consider setting up logging and implementing proper error handling patterns.
¿Qué hemos aprendido?
Este artículo demuestra cómo abrir y leer archivos de Excel, como XLS y XLSX, en C# usando IronXL. IronXL doesn't require Microsoft Excel to be installed on the system for Excel-related tasks, making it perfect for Docker deployments and Azure functions.
IronXL provides a comprehensive solution for Excel-related tasks programmatically, including formula calculation, string sorting, trimming, finding and replacing, merging and unmerging, saving files, and more. You can also set cell data formats, work with conditional formatting, and create charts.
For advanced features, explore grouping and ungrouping, named ranges, hyperlinks, and protecting Excel files. The complete API Reference provides detailed documentation for all features.
IronXL is available for a free 30-day trial and can be licensed for commercial use. IronXL's Lite package starts from $799. For additional resources, visit the tutorials section or explore code examples for common scenarios.
Preguntas Frecuentes
¿Cómo puedo abrir archivos de Excel en C# sin usar Interop?
Puede abrir archivos de Excel en C# sin usar Interop utilizando la biblioteca IronXL. Use el método WorkBook.Load para cargar un archivo de Excel en una instancia de WorkBook, lo que le permite acceder y manipular datos dentro del archivo.
¿Qué formatos de archivo son compatibles con esta biblioteca de Excel para C#?
IronXL admite una variedad de formatos de archivo de Excel, incluidos XLS, XLSX, CSV y TSV. Esto permite a los desarrolladores abrir, leer y escribir en estos formatos de manera flexible dentro de sus aplicaciones C#.
¿Puedo editar archivos de Excel en C# usando esta biblioteca?
Sí, puede editar archivos de Excel usando IronXL. Después de cargar un libro de trabajo, puede modificar datos, agregar nuevas hojas de trabajo y luego guardar los cambios en el archivo o exportarlo en varios formatos.
¿Cómo instalo esta biblioteca para usarla en mi proyecto C#?
Para instalar IronXL en su proyecto C#, puede usar el Administrador de paquetes NuGet en Visual Studio para agregar la biblioteca. Alternativamente, puede descargar el DLL de Excel for .NET y hacer referencia a él en su proyecto.
¿Es posible cifrar archivos de Excel con esta biblioteca?
Sí, IronXL le permite cifrar y descifrar archivos de Excel. Puede asegurar sus documentos de Excel con contraseñas para proteger datos sensibles durante las operaciones de archivo.
¿Esta biblioteca admite recálculos de fórmulas en hojas de Excel?
IronXL admite recálculos automáticos de fórmulas, asegurando que cualquier cambio en los datos actualice automáticamente las fórmulas, como en Excel.
¿Cómo puedo leer valores de celdas específicas en una hoja de trabajo de Excel usando esta biblioteca?
Para leer valores de celdas específicas utilizando IronXL, puede hacer referencia a la celda utilizando la notación de Excel. Por ejemplo, sheet["A1"].StringValue recuperará el valor de cadena de la celda A1.
¿Puede esta biblioteca ser utilizada a través de diferentes sistemas operativos?
Sí, IronXL es compatible con múltiples sistemas operativos, incluidos Windows, Linux y macOS. También admite la implementación en entornos Docker, Azure y AWS.
¿Cuáles son las ventajas de usar esta biblioteca sobre MS Office Interop?
IronXL ofrece varias ventajas sobre MS Office Interop, como no requerir que Excel esté instalado en el sistema, mejor rendimiento en entornos de servidor y facilidad de uso con aplicaciones modernas .NET.
¿Hay una prueba gratuita disponible para esta biblioteca de Excel en C#?
Sí, IronXL ofrece una prueba gratuita de 30 días, permitiéndole probar sus características y capacidades antes de decidir sobre una licencia comercial para sus proyectos.



