Cómo leer archivos de Excel en C# sin interoperabilidad: Guía completa para desarrolladores
Domina la manipulación de archivos Excel en C# usando IronXL, la potente biblioteca .NET que lee, valida y exporta datos de hojas de cálculo sin requerir la instalación de Microsoft Office. Este tutorial completo demuestra operaciones prácticas en Excel, incluyendo validación de datos, conversión de base de datos e integración con API REST.
Inicio Rápido: Leer una Celda con IronXL en una Línea
En solo una línea, puedes cargar un libro de Excel y recuperar el valor de una celda usando IronXL. Está diseñado para ser fácil: sin Interop, sin configuraciones complejas, solo acceso rápido a tus datos.
Empieza a crear PDF con NuGet ahora:
Instalar IronXL con el gestor de paquetes NuGet
Copie y ejecute este fragmento de código.
var value = IronXL.WorkBook.Load("file.xlsx").GetWorkSheet(0)["A1"].StringValue;Despliegue para probar en su entorno real
Empieza a utilizar IronXL en tu proyecto hoy mismo con una prueba gratuita
¿Cómo configurar IronXL para leer archivos de Excel en C#?
Configurar IronXL para leer archivos de Excel en tu proyecto C# lleva solo unos minutos. La biblioteca soporta ambos formatos .XLS y .XLSX, haciéndola versátil para cualquier tarea relacionada con Excel.
Sigue estos pasos para empezar:
- Descargar la Biblioteca de C# para leer archivos de Excel
- Cargar y leer libros de Excel usando
WorkBook.Load() - Acceder a hojas de trabajo con el método
GetWorkSheet() - Leer los valores de las celdas usando sintaxis intuitiva como
sheet["A1"].Value - Validar y procesar datos de hojas de cálculo programáticamente
- Exportar datos a bases de datos usando Entity Framework
IronXL sobresale en la lectura y edición de documentos de Microsoft Excel con C#. La biblioteca opera de forma independiente: no requiere Excel de Microsoft ni Interop para funcionar. De hecho, IronXL proporciona una API más rápida e intuitiva que Microsoft.Office.Interop.Excel.
IronXL Incluye:
- Soporte dedicado de producto por parte de nuestros ingenieros .NET
- Instalación fácil via Microsoft Visual Studio
- Prueba gratuita para el desarrollo. Licencias de
liteLicense
Leer y crear archivos Excel en C# y VB.NET se vuelve sencillo usando la biblioteca de software IronXL.
Lectura de archivos Excel .XLS y .XLSX con IronXL
Aquí tienes el flujo de trabajo esencial para leer archivos Excel usando IronXL:
- Instalar la Biblioteca de Excel IronXL via paquete NuGet o descargar el .NET Excel DLL
- Usar el método
WorkBook.Load()para leer cualquier documento XLS, XLSX, o CSV - Acceder a los valores de celdas usando sintaxis intuitiva:
sheet["A11"].DecimalValue
:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-1.csusing IronXL;
using System;
using System.Linq;
// Load Excel workbook from file path
WorkBook workBook = WorkBook.Load("test.xlsx");
// Access the first worksheet using LINQ
WorkSheet workSheet = workBook.WorkSheets.First();
// Read integer value from cell A2
int cellValue = workSheet["A2"].IntValue;
Console.WriteLine($"Cell A2 value: {cellValue}");
// Iterate through a range of cells
foreach (var cell in workSheet["A2:A10"])
{
Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text);
}
// Advanced Operations with LINQ
// Calculate sum using built_in Sum() method
decimal sum = workSheet["A2:A10"].Sum();
// Find maximum value using LINQ
decimal max = workSheet["A2:A10"].Max(c => c.DecimalValue);
// Output calculated results
Console.WriteLine($"Sum of A2:A10: {sum}");
Console.WriteLine($"Maximum value: {max}");Este código demuestra varias características clave de IronXL: cargar libros, acceder a celdas por dirección, iterar a través de rangos y realizar cálculos. El método WorkBook.Load() detecta inteligentemente los formatos de archivos, mientras que la sintaxis de rango ["A2:A10"] proporciona una selección de celdas similar a Excel. La integración de LINQ permite consultas y agregaciones de datos potentes en colecciones de celdas.
Los ejemplos de código en este tutorial trabajan con tres hojas de cálculo de Excel de muestra que muestran diferentes escenarios de datos:
Archivos de Excel de muestra (GDP.xlsx, People.xlsx, y PopulationByState.xlsx) usados a lo largo de este tutorial para demostrar varias operaciones de IronXL.
¿Cómo puedo instalar la biblioteca C# IronXL?
Instalar la biblioteca IronXL.Excel añade funcionalidad completa de Excel a tus proyectos de .NET framework. Elige entre la instalación de NuGet o la integración manual de DLL.
Instalación del paquete NuGet IronXL
- En Visual Studio, haz clic derecho en tu proyecto y selecciona "Administrar paquetes NuGet..."
- Busca "IronXL.Excel" en la pestaña Examinar
- Haz clic en el botón Instalar para añadir IronXL a tu proyecto
Instalar IronXL a través del Administrador de Paquetes NuGet de Visual Studio proporciona gestión automática de dependencias.
Alternativamente, instala IronXL usando la Consola del Administrador de Paquetes:
- Abre la Consola del Administrador de Paquetes (Herramientas → Gestor de Paquetes NuGet → Consola del Administrador de Paquetes)
- Ejecuta el comando de instalación:
Install-Package IronXL.Excel
También puedes ver los detalles del paquete en el sitio web de NuGet.
Instalación manual
Para una instalación manual, descarga el .NET Excel DLL de IronXL y referencia directamente en tu proyecto de Visual Studio.
¿Cómo cargo y leo un libro de Excel?
La clase WorkBook representa un archivo de Excel completo. Carga los archivos de Excel usando el método WorkBook.Load(), que acepta rutas de archivos para los formatos XLS, XLSX, CSV y TSV.
:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-2.csusing IronXL;
using System;
using System.Linq;
// Load Excel file from specified path
WorkBook workBook = WorkBook.Load(@"Spreadsheets\GDP.xlsx");
Console.WriteLine("Workbook loaded successfully.");
// Access specific worksheet by name
WorkSheet sheet = workBook.GetWorkSheet("Sheet1");
// Read and display cell value
string cellValue = sheet["A1"].StringValue;
Console.WriteLine($"Cell A1 contains: {cellValue}");
// Perform additional operations
// Count non_empty cells in column A
int rowCount = sheet["A:A"].Count(cell => !cell.IsEmpty);
Console.WriteLine($"Column A has {rowCount} non_empty cells");Cada WorkBook contiene múltiples objetos WorkSheet que representan hojas de Excel individuales. Accede a las hojas de trabajo por nombre usando GetWorkSheet():
:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-3.csusing IronXL;
using System;
// Get worksheet by name
WorkSheet workSheet = workBook.GetWorkSheet("GDPByCountry");
Console.WriteLine("Worksheet 'GDPByCountry' not found");
// List available worksheets
foreach (var sheet in workBook.WorkSheets)
{
Console.WriteLine($"Available: {sheet.Name}");
}¿Cómo crear nuevos documentos Excel en C#?
Crea nuevos documentos de Excel construyendo un objeto WorkBook con tu formato de archivo deseado. IronXL soporta tanto formatos modernos XLSX como legados XLS.
:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-4.csusing IronXL;
// Create new XLSX workbook (recommended format)
WorkBook workBook = WorkBook.Create(ExcelFileFormat.XLSX);
// Set workbook metadata
workBook.Metadata.Author = "Your Application";
workBook.Metadata.Comments = "Generated by IronXL";
// Create new XLS workbook for legacy support
WorkBook legacyWorkBook = WorkBook.Create(ExcelFileFormat.XLS);
// Save the workbook
workBook.SaveAs("NewDocument.xlsx");Nota: Usa ExcelFileFormat.XLS solo cuando se requiera compatibilidad con Excel 2003 y anteriores.
¿Cómo puedo agregar hojas de trabajo a un documento de Excel?
Un WorkBook de IronXL contiene una colección de hojas de trabajo. Entender esta estructura ayuda al crear archivos de Excel con múltiples hojas.
Representación visual de la estructura del WorkBook que contiene múltiples objetos WorkSheet en IronXL.
Crea nuevas hojas de trabajo usando CreateWorkSheet():
:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-5.csusing IronXL;
// Create multiple worksheets with descriptive names
WorkSheet summarySheet = workBook.CreateWorkSheet("Summary");
WorkSheet dataSheet = workBook.CreateWorkSheet("RawData");
WorkSheet chartSheet = workBook.CreateWorkSheet("Charts");
// Set the active worksheet
workBook.SetActiveTab(0); // Makes "Summary" the active sheet
// Access default worksheet (first sheet)
WorkSheet defaultSheet = workBook.DefaultWorkSheet;¿Cómo leo y edito valores de celda?
Leer y editar una sola celda
Accede a las celdas individuales a través de la propiedad indexada de la hoja de trabajo. La clase Cell de IronXL proporciona propiedades de valor fuertemente tipadas.
:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-6.csusing IronXL;
using System;
using System.Linq;
// Load workbook and get worksheet
WorkBook workBook = WorkBook.Load("test.xlsx");
WorkSheet workSheet = workBook.DefaultWorkSheet;
// Access cell B1
IronXL.Cell cell = workSheet["B1"].First();
// Read cell value with type safety
string textValue = cell.StringValue;
int intValue = cell.IntValue;
decimal decimalValue = cell.DecimalValue;
DateTime? dateValue = cell.DateTimeValue;
// Check cell data type
if (cell.IsNumeric)
{
Console.WriteLine($"Numeric value: {cell.DecimalValue}");
}
else if (cell.IsText)
{
Console.WriteLine($"Text value: {cell.StringValue}");
}La clase Cell ofrece múltiples propiedades para diferentes tipos de datos, convirtiendo valores automáticamente cuando es posible. Para más operaciones de celda, ver el tutorial de formateo de celda.
:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-7.cs// Write different data types to cells
workSheet["A1"].Value = "Product Name"; // String
workSheet["B1"].Value = 99.95m; // Decimal
workSheet["C1"].Value = DateTime.Today; // Date
workSheet["D1"].Formula = "=B1*1.2"; // Formula
// Format cells
workSheet["B1"].FormatString = "$#,##0.00"; // Currency format
workSheet["C1"].FormatString = "yyyy-MM-dd";// Date format
// Save changes
workBook.Save();¿Cómo puedo trabajar con rangos de celdas?
La clase Range representa una colección de celdas, permitiendo operaciones en masa en datos de Excel.
:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-8.cs// Select range using Excel notation
Range range = workSheet["D2:D101"];
// Alternative: Use Range class for dynamic selection
Range dynamicRange = workSheet.GetRange("D2:D101"); // Row 2_101, Column D
// Perform bulk operations
range.Value = 0; // Set all cells to 0Procesa rangos eficientemente usando bucles cuando se conoce el conteo de celdas:
// Data validation example
public class ValidationResult
{
public int Row { get; set; }
public string PhoneError { get; set; }
public string EmailError { get; set; }
public string DateError { get; set; }
public bool IsValid => string.IsNullOrEmpty(PhoneError) &&
string.IsNullOrEmpty(EmailError) &&
string.IsNullOrEmpty(DateError);
}
// Validate data in rows 2-101
var results = new List<ValidationResult>();
for (int row = 2; row <= 101; row++)
{
var result = new ValidationResult { Row = row };
// Get row data efficiently
var phoneCell = workSheet[$"B{row}"];
var emailCell = workSheet[$"D{row}"];
var dateCell = workSheet[$"E{row}"];
// Validate phone number
if (!IsValidPhoneNumber(phoneCell.StringValue))
result.PhoneError = "Invalid phone format";
// Validate email
if (!IsValidEmail(emailCell.StringValue))
result.EmailError = "Invalid email format";
// Validate date
if (!dateCell.IsDateTime)
result.DateError = "Invalid date format";
results.Add(result);
}
// Helper methods
bool IsValidPhoneNumber(string phone) =>
System.Text.RegularExpressions.Regex.IsMatch(phone, @"^\d{3}-\d{3}-\d{4}$");
bool IsValidEmail(string email) =>
email.Contains("@") && email.Contains(".");// Data validation example
public class ValidationResult
{
public int Row { get; set; }
public string PhoneError { get; set; }
public string EmailError { get; set; }
public string DateError { get; set; }
public bool IsValid => string.IsNullOrEmpty(PhoneError) &&
string.IsNullOrEmpty(EmailError) &&
string.IsNullOrEmpty(DateError);
}
// Validate data in rows 2-101
var results = new List<ValidationResult>();
for (int row = 2; row <= 101; row++)
{
var result = new ValidationResult { Row = row };
// Get row data efficiently
var phoneCell = workSheet[$"B{row}"];
var emailCell = workSheet[$"D{row}"];
var dateCell = workSheet[$"E{row}"];
// Validate phone number
if (!IsValidPhoneNumber(phoneCell.StringValue))
result.PhoneError = "Invalid phone format";
// Validate email
if (!IsValidEmail(emailCell.StringValue))
result.EmailError = "Invalid email format";
// Validate date
if (!dateCell.IsDateTime)
result.DateError = "Invalid date format";
results.Add(result);
}
// Helper methods
bool IsValidPhoneNumber(string phone) =>
System.Text.RegularExpressions.Regex.IsMatch(phone, @"^\d{3}-\d{3}-\d{4}$");
bool IsValidEmail(string email) =>
email.Contains("@") && email.Contains(".");¿Cómo agrego fórmulas a hojas de cálculo de Excel?
Aplica fórmulas de Excel usando la propiedad Formula. IronXL soporta la sintaxis estándar de fórmulas de Excel.
:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-9.csusing IronXL;
// Add formulas to calculate percentages
int lastRow = 50;
for (int row = 2; row < lastRow; row++)
{
// Calculate percentage: current value / total
workSheet[$"C{row}"].Formula = $"=B{row}/B{lastRow}";
// Format as percentage
workSheet[$"C{row}"].FormatString = "0.00%";
}
// Add summary formulas
workSheet["B52"].Formula = "=SUM(B2:B50)"; // Sum
workSheet["B53"].Formula = "=AVERAGE(B2:B50)"; // Average
workSheet["B54"].Formula = "=MAX(B2:B50)"; // Maximum
workSheet["B55"].Formula = "=MIN(B2:B50)"; // Minimum
// Force formula evaluation
workBook.EvaluateAll();Para editar fórmulas existentes, explora el tutorial de fórmulas de Excel.
¿Cómo puedo validar los datos de una hoja de cálculo?
IronXL permite la validación completa de datos para hojas de cálculo. Este ejemplo valida números de teléfono, correos electrónicos, y fechas usando bibliotecas externas y funcionalidad integrada de C#.
using System.Text.RegularExpressions;
using IronXL;
// Validation implementation
for (int i = 2; i <= 101; i++)
{
var result = new PersonValidationResult { Row = i };
results.Add(result);
// Get cells for current person
var cells = workSheet[$"A{i}:E{i}"].ToList();
// Validate phone (column B)
string phone = cells[1].StringValue;
if (!Regex.IsMatch(phone, @"^\+?1?\d{10,14}$"))
{
result.PhoneNumberErrorMessage = "Invalid phone format";
}
// Validate email (column D)
string email = cells[3].StringValue;
if (!Regex.IsMatch(email, @"^[^@\s]+@[^@\s]+\.[^@\s]+$"))
{
result.EmailErrorMessage = "Invalid email address";
}
// Validate date (column E)
if (!cells[4].IsDateTime)
{
result.DateErrorMessage = "Invalid date format";
}
}using System.Text.RegularExpressions;
using IronXL;
// Validation implementation
for (int i = 2; i <= 101; i++)
{
var result = new PersonValidationResult { Row = i };
results.Add(result);
// Get cells for current person
var cells = workSheet[$"A{i}:E{i}"].ToList();
// Validate phone (column B)
string phone = cells[1].StringValue;
if (!Regex.IsMatch(phone, @"^\+?1?\d{10,14}$"))
{
result.PhoneNumberErrorMessage = "Invalid phone format";
}
// Validate email (column D)
string email = cells[3].StringValue;
if (!Regex.IsMatch(email, @"^[^@\s]+@[^@\s]+\.[^@\s]+$"))
{
result.EmailErrorMessage = "Invalid email address";
}
// Validate date (column E)
if (!cells[4].IsDateTime)
{
result.DateErrorMessage = "Invalid date format";
}
}Guardar resultados de validación en una nueva hoja de trabajo:
// Create results worksheet
var resultsSheet = workBook.CreateWorkSheet("ValidationResults");
// Add headers
resultsSheet["A1"].Value = "Row";
resultsSheet["B1"].Value = "Valid";
resultsSheet["C1"].Value = "Phone Error";
resultsSheet["D1"].Value = "Email Error";
resultsSheet["E1"].Value = "Date Error";
// Style headers
resultsSheet["A1:E1"].Style.Font.Bold = true;
resultsSheet["A1:E1"].Style.SetBackgroundColor("#4472C4");
resultsSheet["A1:E1"].Style.Font.Color = "#FFFFFF";
// Output validation results
for (int i = 0; i < results.Count; i++)
{
var result = results[i];
int outputRow = i + 2;
resultsSheet[$"A{outputRow}"].Value = result.Row;
resultsSheet[$"B{outputRow}"].Value = result.IsValid ? "Yes" : "No";
resultsSheet[$"C{outputRow}"].Value = result.PhoneNumberErrorMessage ?? "";
resultsSheet[$"D{outputRow}"].Value = result.EmailErrorMessage ?? "";
resultsSheet[$"E{outputRow}"].Value = result.DateErrorMessage ?? "";
// Highlight invalid rows
if (!result.IsValid)
{
resultsSheet[$"A{outputRow}:E{outputRow}"].Style.SetBackgroundColor("#FFE6E6");
}
}
// Auto-fit columns
for (int col = 0; col < 5; col++)
{
resultsSheet.AutoSizeColumn(col);
}
// Save validated workbook
workBook.SaveAs(@"Spreadsheets\PeopleValidated.xlsx");// Create results worksheet
var resultsSheet = workBook.CreateWorkSheet("ValidationResults");
// Add headers
resultsSheet["A1"].Value = "Row";
resultsSheet["B1"].Value = "Valid";
resultsSheet["C1"].Value = "Phone Error";
resultsSheet["D1"].Value = "Email Error";
resultsSheet["E1"].Value = "Date Error";
// Style headers
resultsSheet["A1:E1"].Style.Font.Bold = true;
resultsSheet["A1:E1"].Style.SetBackgroundColor("#4472C4");
resultsSheet["A1:E1"].Style.Font.Color = "#FFFFFF";
// Output validation results
for (int i = 0; i < results.Count; i++)
{
var result = results[i];
int outputRow = i + 2;
resultsSheet[$"A{outputRow}"].Value = result.Row;
resultsSheet[$"B{outputRow}"].Value = result.IsValid ? "Yes" : "No";
resultsSheet[$"C{outputRow}"].Value = result.PhoneNumberErrorMessage ?? "";
resultsSheet[$"D{outputRow}"].Value = result.EmailErrorMessage ?? "";
resultsSheet[$"E{outputRow}"].Value = result.DateErrorMessage ?? "";
// Highlight invalid rows
if (!result.IsValid)
{
resultsSheet[$"A{outputRow}:E{outputRow}"].Style.SetBackgroundColor("#FFE6E6");
}
}
// Auto-fit columns
for (int col = 0; col < 5; col++)
{
resultsSheet.AutoSizeColumn(col);
}
// Save validated workbook
workBook.SaveAs(@"Spreadsheets\PeopleValidated.xlsx");¿Cómo exportar datos de Excel a una base de datos?
Usa IronXL con Entity Framework para exportar datos de hojas de cálculo directamente a bases de datos. Este ejemplo demuestra la exportación de datos de PIB de países a SQLite.
using System;
using System.ComponentModel.DataAnnotations;
using Microsoft.EntityFrameworkCore;
using IronXL;
// Define entity model
public class Country
{
[Key]
public Guid Id { get; set; } = Guid.NewGuid();
[Required]
[MaxLength(100)]
public string Name { get; set; }
[Range(0, double.MaxValue)]
public decimal GDP { get; set; }
public DateTime ImportedDate { get; set; } = DateTime.UtcNow;
}using System;
using System.ComponentModel.DataAnnotations;
using Microsoft.EntityFrameworkCore;
using IronXL;
// Define entity model
public class Country
{
[Key]
public Guid Id { get; set; } = Guid.NewGuid();
[Required]
[MaxLength(100)]
public string Name { get; set; }
[Range(0, double.MaxValue)]
public decimal GDP { get; set; }
public DateTime ImportedDate { get; set; } = DateTime.UtcNow;
}Configura el contexto de Entity Framework para operaciones de base de datos:
public class CountryContext : DbContext
{
public DbSet<Country> Countries { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
// Configure SQLite connection
optionsBuilder.UseSqlite("Data Source=CountryGDP.db");
// Enable sensitive data logging in development
#if DEBUG
optionsBuilder.EnableSensitiveDataLogging();
#endif
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// Configure decimal precision
modelBuilder.Entity<Country>()
.Property(c => c.GDP)
.HasPrecision(18, 2);
}
}public class CountryContext : DbContext
{
public DbSet<Country> Countries { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
// Configure SQLite connection
optionsBuilder.UseSqlite("Data Source=CountryGDP.db");
// Enable sensitive data logging in development
#if DEBUG
optionsBuilder.EnableSensitiveDataLogging();
#endif
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// Configure decimal precision
modelBuilder.Entity<Country>()
.Property(c => c.GDP)
.HasPrecision(18, 2);
}
}Microsoft.EntityFrameworkCore.SqlServer para SQL Server) y modifique la configuración de la conexión según corresponda.Importar datos de Excel a la base de datos:
using System.Threading.Tasks;
using IronXL;
using Microsoft.EntityFrameworkCore;
public async Task ImportGDPDataAsync()
{
try
{
// Load Excel file
var workBook = WorkBook.Load(@"Spreadsheets\GDP.xlsx");
var workSheet = workBook.GetWorkSheet("GDPByCountry");
using (var context = new CountryContext())
{
// Ensure database exists
await context.Database.EnsureCreatedAsync();
// Clear existing data (optional)
await context.Database.ExecuteSqlRawAsync("DELETE FROM Countries");
// Import data with progress tracking
int totalRows = 213;
for (int row = 2; row <= totalRows; row++)
{
// Read country data
var countryName = workSheet[$"A{row}"].StringValue;
var gdpValue = workSheet[$"B{row}"].DecimalValue;
// Skip empty rows
if (string.IsNullOrWhiteSpace(countryName))
continue;
// Create and add entity
var country = new Country
{
Name = countryName.Trim(),
GDP = gdpValue * 1_000_000 // Convert to actual value if in millions
};
await context.Countries.AddAsync(country);
// Save in batches for performance
if (row % 50 == 0)
{
await context.SaveChangesAsync();
Console.WriteLine($"Imported {row - 1} of {totalRows} countries");
}
}
// Save remaining records
await context.SaveChangesAsync();
Console.WriteLine($"Successfully imported {await context.Countries.CountAsync()} countries");
}
}
catch (Exception ex)
{
Console.WriteLine($"Import failed: {ex.Message}");
throw;
}
}using System.Threading.Tasks;
using IronXL;
using Microsoft.EntityFrameworkCore;
public async Task ImportGDPDataAsync()
{
try
{
// Load Excel file
var workBook = WorkBook.Load(@"Spreadsheets\GDP.xlsx");
var workSheet = workBook.GetWorkSheet("GDPByCountry");
using (var context = new CountryContext())
{
// Ensure database exists
await context.Database.EnsureCreatedAsync();
// Clear existing data (optional)
await context.Database.ExecuteSqlRawAsync("DELETE FROM Countries");
// Import data with progress tracking
int totalRows = 213;
for (int row = 2; row <= totalRows; row++)
{
// Read country data
var countryName = workSheet[$"A{row}"].StringValue;
var gdpValue = workSheet[$"B{row}"].DecimalValue;
// Skip empty rows
if (string.IsNullOrWhiteSpace(countryName))
continue;
// Create and add entity
var country = new Country
{
Name = countryName.Trim(),
GDP = gdpValue * 1_000_000 // Convert to actual value if in millions
};
await context.Countries.AddAsync(country);
// Save in batches for performance
if (row % 50 == 0)
{
await context.SaveChangesAsync();
Console.WriteLine($"Imported {row - 1} of {totalRows} countries");
}
}
// Save remaining records
await context.SaveChangesAsync();
Console.WriteLine($"Successfully imported {await context.Countries.CountAsync()} countries");
}
}
catch (Exception ex)
{
Console.WriteLine($"Import failed: {ex.Message}");
throw;
}
}¿Cómo puedo importar datos de API en hojas de cálculo de Excel?
Combina IronXL con clientes HTTP para poblar hojas de cálculo con datos de API en vivo. Este ejemplo usa RestClient.Net para obtener datos de países.
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;
using IronXL;
// Define data model matching API response
public class RestCountry
{
public string Name { get; set; }
public long Population { get; set; }
public string Region { get; set; }
public string NumericCode { get; set; }
public List<Language> Languages { get; set; }
}
public class Language
{
public string Name { get; set; }
public string NativeName { get; set; }
}
// Fetch and process API data
public async Task ImportCountryDataAsync()
{
using var httpClient = new HttpClient();
try
{
// Call REST API
var response = await httpClient.GetStringAsync("https://restcountries.com/v3.1/all");
var countries = JsonConvert.DeserializeObject<List<RestCountry>>(response);
// Create new workbook
var workBook = WorkBook.Create(ExcelFileFormat.XLSX);
var workSheet = workBook.CreateWorkSheet("Countries");
// Add headers with styling
string[] headers = { "Country", "Population", "Region", "Code", "Language 1", "Language 2", "Language 3" };
for (int col = 0; col < headers.Length; col++)
{
var headerCell = workSheet[0, col];
headerCell.Value = headers[col];
headerCell.Style.Font.Bold = true;
headerCell.Style.SetBackgroundColor("#366092");
headerCell.Style.Font.Color = "#FFFFFF";
}
// Import country data
await ProcessCountryData(countries, workSheet);
// Save workbook
workBook.SaveAs("CountriesFromAPI.xlsx");
}
catch (Exception ex)
{
Console.WriteLine($"API import failed: {ex.Message}");
}
}using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;
using IronXL;
// Define data model matching API response
public class RestCountry
{
public string Name { get; set; }
public long Population { get; set; }
public string Region { get; set; }
public string NumericCode { get; set; }
public List<Language> Languages { get; set; }
}
public class Language
{
public string Name { get; set; }
public string NativeName { get; set; }
}
// Fetch and process API data
public async Task ImportCountryDataAsync()
{
using var httpClient = new HttpClient();
try
{
// Call REST API
var response = await httpClient.GetStringAsync("https://restcountries.com/v3.1/all");
var countries = JsonConvert.DeserializeObject<List<RestCountry>>(response);
// Create new workbook
var workBook = WorkBook.Create(ExcelFileFormat.XLSX);
var workSheet = workBook.CreateWorkSheet("Countries");
// Add headers with styling
string[] headers = { "Country", "Population", "Region", "Code", "Language 1", "Language 2", "Language 3" };
for (int col = 0; col < headers.Length; col++)
{
var headerCell = workSheet[0, col];
headerCell.Value = headers[col];
headerCell.Style.Font.Bold = true;
headerCell.Style.SetBackgroundColor("#366092");
headerCell.Style.Font.Color = "#FFFFFF";
}
// Import country data
await ProcessCountryData(countries, workSheet);
// Save workbook
workBook.SaveAs("CountriesFromAPI.xlsx");
}
catch (Exception ex)
{
Console.WriteLine($"API import failed: {ex.Message}");
}
}La API devuelve datos JSON en este formato:
Respuesta JSON de muestra de la REST Countries API mostrando información jerárquica de países.
Procesa y escribe los datos de API a Excel:
private async Task ProcessCountryData(List<RestCountry> countries, WorkSheet workSheet)
{
for (int i = 0; i < countries.Count; i++)
{
var country = countries[i];
int row = i + 1; // Start from row 1 (after headers)
// Write basic country data
workSheet[$"A{row}"].Value = country.Name;
workSheet[$"B{row}"].Value = country.Population;
workSheet[$"C{row}"].Value = country.Region;
workSheet[$"D{row}"].Value = country.NumericCode;
// Format population with thousands separator
workSheet[$"B{row}"].FormatString = "#,##0";
// Add up to 3 languages
for (int langIndex = 0; langIndex < Math.Min(3, country.Languages?.Count ?? 0); langIndex++)
{
var language = country.Languages[langIndex];
string columnLetter = ((char)('E' + langIndex)).ToString();
workSheet[$"{columnLetter}{row}"].Value = language.Name;
}
// Add conditional formatting for regions
if (country.Region == "Europe")
{
workSheet[$"C{row}"].Style.SetBackgroundColor("#E6F3FF");
}
else if (country.Region == "Asia")
{
workSheet[$"C{row}"].Style.SetBackgroundColor("#FFF2E6");
}
// Show progress every 50 countries
if (i % 50 == 0)
{
Console.WriteLine($"Processed {i} of {countries.Count} countries");
}
}
// Auto-size all columns
for (int col = 0; col < 7; col++)
{
workSheet.AutoSizeColumn(col);
}
}private async Task ProcessCountryData(List<RestCountry> countries, WorkSheet workSheet)
{
for (int i = 0; i < countries.Count; i++)
{
var country = countries[i];
int row = i + 1; // Start from row 1 (after headers)
// Write basic country data
workSheet[$"A{row}"].Value = country.Name;
workSheet[$"B{row}"].Value = country.Population;
workSheet[$"C{row}"].Value = country.Region;
workSheet[$"D{row}"].Value = country.NumericCode;
// Format population with thousands separator
workSheet[$"B{row}"].FormatString = "#,##0";
// Add up to 3 languages
for (int langIndex = 0; langIndex < Math.Min(3, country.Languages?.Count ?? 0); langIndex++)
{
var language = country.Languages[langIndex];
string columnLetter = ((char)('E' + langIndex)).ToString();
workSheet[$"{columnLetter}{row}"].Value = language.Name;
}
// Add conditional formatting for regions
if (country.Region == "Europe")
{
workSheet[$"C{row}"].Style.SetBackgroundColor("#E6F3FF");
}
else if (country.Region == "Asia")
{
workSheet[$"C{row}"].Style.SetBackgroundColor("#FFF2E6");
}
// Show progress every 50 countries
if (i % 50 == 0)
{
Console.WriteLine($"Processed {i} of {countries.Count} countries");
}
}
// Auto-size all columns
for (int col = 0; col < 7; col++)
{
workSheet.AutoSizeColumn(col);
}
}Referencia de objetos y recursos
Explora la completa Referencia de API de IronXL para documentación detallada de clases y características avanzadas.
Tutoriales adicionales para operaciones en Excel:
Resumen
IronXL.Excel es una biblioteca .NET completa para leer y manipular archivos Excel en varios formatos. Opera de forma independiente sin requerir Microsoft Excel ni instalación de Interop.
Para manipulación de hojas de cálculo basada en la nube, también puedes explorar la Biblioteca del Cliente API de Google Sheets para .NET, que complementa las capacidades de archivos locales de IronXL.
¿Listo para implementar automatización de Excel en tus proyectos C#? Descarga IronXL o explora opciones de licencias para uso en producción.
Preguntas Frecuentes
¿Cómo puedo leer archivos de Excel en C# sin usar Microsoft Office?
Puede usar IronXL para leer archivos de Excel en C# sin necesidad de Microsoft Office. IronXL proporciona métodos como WorkBook.Load() para abrir archivos de Excel y le permite acceder y manipular datos usando una sintaxis intuitiva.
¿Qué formatos de archivos de Excel se pueden leer usando C#?
Con IronXL, puede leer archivos en formatos XLS y XLSX en C#. La biblioteca detecta automáticamente el formato del archivo y lo procesa en consecuencia usando el método WorkBook.Load().
¿Cómo valido datos de Excel en C#?
IronXL le permite validar datos de Excel programáticamente en C# iterando a través de las celdas y aplicando lógica como expresiones regulares para correos electrónicos o funciones de validación personalizadas. Puede generar informes usando CreateWorkSheet().
¿Cómo puedo exportar datos de Excel a una base de datos SQL usando C#?
Para exportar datos de Excel a una base de datos SQL, use IronXL para leer datos de Excel con los métodos WorkBook.Load() y GetWorkSheet(), luego itere a través de las celdas para transferir datos a su base de datos usando Entity Framework.
¿Puedo integrar la funcionalidad de Excel con aplicaciones ASP.NET Core?
Sí, IronXL admite la integración con aplicaciones ASP.NET Core. Puede usar las clases WorkBook y WorkSheet en sus controladores para manejar cargas de archivos de Excel, generar informes y más.
¿Es posible agregar fórmulas a hojas de cálculo de Excel usando C#?
IronXL le permite agregar fórmulas a hojas de cálculo de Excel programáticamente. Puede establecer una fórmula usando la propiedad Formula, como cell.Formula = "=SUM(A1:A10)" y calcular resultados con workBook.EvaluateAll().
¿Cómo puedo llenar archivos de Excel con datos de una API REST?
Para llenar archivos de Excel con datos de una API REST, use IronXL junto con un cliente HTTP para obtener datos de la API, luego escríbalos en Excel usando métodos como sheet["A1"].Value. IronXL gestiona el formato y la estructura de Excel.
¿Cuáles son las opciones de licencia para usar bibliotecas de Excel en entornos de producción?
IronXL ofrece una prueba gratuita para fines de desarrollo, mientras que las licencias de producción comienzan desde $749. Estas licencias incluyen soporte técnico dedicado y permiten la implementación en varios entornos sin necesitar licencias adicionales de Office.






