Cómo importar archivos Excel en C#

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

Como desarrolladores, a menudo necesitamos importar datos de archivos Excel y utilizarlos para cumplir nuestros requisitos de gestión de datos y aplicaciones. Sin necesidad de muchas líneas de código, IronXL nos ofrece una forma sencilla de importar exactamente los datos que necesitamos directamente en un proyecto C# y, a continuación, manipularlos mediante programación.


Primer paso

1. Importar datos con la biblioteca IronXL

Importe datos utilizando las funciones provistas por la librería IronXL Excel, que utilizaremos en este tutorial. El software está disponible gratuitamente para su desarrollo.

Instale en su Proyecto C# mediante DLL Descargar o navegar utilizando el paquete NuGet.

Install-Package IronXL.Excel


Tutorial

2. Hoja de trabajo Access para el proyecto

Para las necesidades de nuestro proyecto de hoy, vamos a importar datos de Excel en nuestra aplicación C#, utilizando el software IronXL instalado en el paso 1.

Para el paso 2, cargaremos nuestro Excel WorkBook en nuestro proyecto CSharp utilizando el comando WorkBook.Load() función de IronXL. Pasamos la ruta del Libro de Excel como un parámetro de cadena en esta función, así:

//load Excel file
WorkBook wb = WorkBook.Load("Path");
//load Excel file
WorkBook wb = WorkBook.Load("Path");
'load Excel file
Dim wb As WorkBook = WorkBook.Load("Path")
VB   C#

El archivo Excel de la ruta especificada se cargará en wb.

A continuación, necesitamos acceder a una WorkSheet específica del archivo Excel cuyos datos se importarán al proyecto. Para ello, podemos utilizar la función GetWorkSheet() función de IronXL. Pasaremos el nombre de la hoja como un parámetro de cadena en esta función para especificar qué hoja del Libro de Trabajo debe importarse.

//specify sheet name of Excel WorkBook
WorkSheet ws = wb.GetWorkSheet("SheetName");
//specify sheet name of Excel WorkBook
WorkSheet ws = wb.GetWorkSheet("SheetName");
'specify sheet name of Excel WorkBook
Dim ws As WorkSheet = wb.GetWorkSheet("SheetName")
VB   C#

El WorkSheet se importará como ws, y wb es el WorkBook que hemos definido en el ejemplo de código anterior.

También existen las siguientes formas alternativas de importar una hoja de trabajo de Excel al proyecto.

/**
Import WorkSheet 
anchor-access-worksheet-for-project
**/
//by sheet indexing
WorkBook.WorkSheets [SheetIndex];
//get default  WorkSheet
WorkBook.DefaultWorkSheet;
//get first WorkSheet
WorkBook.WorkSheets.First();
//for the first or default sheet:
WorkBook.WorkSheets.FirstOrDefault();
/**
Import WorkSheet 
anchor-access-worksheet-for-project
**/
//by sheet indexing
WorkBook.WorkSheets [SheetIndex];
//get default  WorkSheet
WorkBook.DefaultWorkSheet;
//get first WorkSheet
WorkBook.WorkSheets.First();
//for the first or default sheet:
WorkBook.WorkSheets.FirstOrDefault();
'''
'''Import WorkSheet 
'''anchor-access-worksheet-for-project
'''*
'by sheet indexing
WorkBook.WorkSheets (SheetIndex)
'get default  WorkSheet
WorkBook.DefaultWorkSheet
'get first WorkSheet
WorkBook.WorkSheets.First()
'for the first or default sheet:
WorkBook.WorkSheets.FirstOrDefault()
VB   C#

Ahora, podemos importar fácilmente cualquier tipo de datos de los archivos Excel especificados. Veamos todos los aspectos posibles que utilizamos para importar datos de archivos Excel en nuestro proyecto.


3. Importar datos de Excel en C#

Este es el aspecto básico de la importación de datos de archivos Excel en nuestro proyecto.

Para ello, podemos utilizar un sistema de direccionamiento de celdas para especificar qué datos de celdas necesitamos importar. Devolverá el valor de una dirección de celda específica del archivo Excel.

WorkSheet ["Cell Address"];
WorkSheet ["Cell Address"];
WorkSheet ("Cell Address")
VB   C#

También podemos importar datos de celdas de archivos Excel utilizando el índice de filas y columnas. Esta línea de código devolverá el valor del índice de fila y columna especificados.

WorkSheet.Rows [RowIndex].Columns [ColumnIndex]
WorkSheet.Rows [RowIndex].Columns [ColumnIndex]
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'WorkSheet.Rows [RowIndex].Columns [ColumnIndex]
VB   C#

Si queremos asignar valores de celdas importadas a variables, podemos utilizar este código.

/**
Import Data by Cell Address
anchor-import-excel-data-in-c-num
**/
//by cell addressing
string val = WorkSheet ["Cell Address"].ToString();
//by row and column indexing
string val = WorkSheet.Rows [RowIndex].Columns [ColumnIndex].Value.ToString();
/**
Import Data by Cell Address
anchor-import-excel-data-in-c-num
**/
//by cell addressing
string val = WorkSheet ["Cell Address"].ToString();
//by row and column indexing
string val = WorkSheet.Rows [RowIndex].Columns [ColumnIndex].Value.ToString();
'''
'''Import Data by Cell Address
'''anchor-import-excel-data-in-c-num
'''*
'by cell addressing
Dim val As String = WorkSheet ("Cell Address").ToString()
'by row and column indexing
Dim val As String = WorkSheet.Rows (RowIndex).Columns (ColumnIndex).Value.ToString()
VB   C#

En los ejemplos anteriores, el índice de filas y columnas empieza en 0.


4. Importar datos Excel de un rango específico

Si queremos importar datos en un rango específico desde un Libro de Excel, se puede hacer fácilmente utilizando la función range. Para definir el rango, necesitamos describir la dirección de la celda inicial y de la celda final. De este modo, devolverá todos los valores de celda que se encuentren en el rango especificado.

WorkSheet ["starting Cell Address : Ending Cell Address"];
WorkSheet ["starting Cell Address : Ending Cell Address"];
WorkSheet ("starting Cell Address : Ending Cell Address")
VB   C#

Más información sobre el trabajo con rango en archivos Excel consulte los ejemplos de código proporcionados.

/**
Import Data by Range
anchor-import-excel-data-of-specific-range
**/
using IronXL;
static void Main(string [] args)
{
    //import Excel WorkBook
    WorkBook wb = WorkBook.Load("sample.xlsx");
    //specify WorkSheet
    WorkSheet ws = wb.GetWorkSheet("Sheet1");
    //import data of specific cell
    string val = ws ["A4"].Value.ToString();
    Console.WriteLine("Import Value of A4 Cell address: {0}",val);
    Console.WriteLine("import Values in Range From B3 To B9 :\n");
    //import data in specific range
    foreach (var item in ws ["B3:B9"])
    {
        Console.WriteLine(item.Value.ToString());
    }
    Console.ReadKey();
}
/**
Import Data by Range
anchor-import-excel-data-of-specific-range
**/
using IronXL;
static void Main(string [] args)
{
    //import Excel WorkBook
    WorkBook wb = WorkBook.Load("sample.xlsx");
    //specify WorkSheet
    WorkSheet ws = wb.GetWorkSheet("Sheet1");
    //import data of specific cell
    string val = ws ["A4"].Value.ToString();
    Console.WriteLine("Import Value of A4 Cell address: {0}",val);
    Console.WriteLine("import Values in Range From B3 To B9 :\n");
    //import data in specific range
    foreach (var item in ws ["B3:B9"])
    {
        Console.WriteLine(item.Value.ToString());
    }
    Console.ReadKey();
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

El código anterior muestra la siguiente salida:

Con los valores del fichero Excel sample.xlsx como:


5. Importar datos de Excel mediante funciones agregadas

También podemos aplicar funciones de agregación a ficheros Excel e importar los datos resultantes de estas funciones de agregación. Aquí tienes algunos ejemplos de las distintas funciones y cómo utilizarlas.

  • Suma()`
 //to find the sum of specific cell range 
WorkSheet ["Starting Cell Address : Ending Cell Address"].Sum();
 //to find the sum of specific cell range 
WorkSheet ["Starting Cell Address : Ending Cell Address"].Sum();
'to find the sum of specific cell range 
WorkSheet ("Starting Cell Address : Ending Cell Address").Sum()
VB   C#
  • Promedio()
 //to find the average of specific cell range 
WorkSheet ["Starting Cell Address : Ending Cell Address"].Avg()
 //to find the average of specific cell range 
WorkSheet ["Starting Cell Address : Ending Cell Address"].Avg()
'to find the average of specific cell range 
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'WorkSheet ["Starting Cell Address : Ending Cell Address"].Avg()
VB   C#
  • Min()
 //to find the Min In specific cell range 
WorkSheet ["Starting Cell Address : Ending Cell Address"].Min()
 //to find the Min In specific cell range 
WorkSheet ["Starting Cell Address : Ending Cell Address"].Min()
'to find the Min In specific cell range 
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'WorkSheet ["Starting Cell Address : Ending Cell Address"].Min()
VB   C#
  • Max()
 //to find the Max in specific cell range 
WorkSheet ["Starting Cell Address : Ending Cell Address"].Max()
 //to find the Max in specific cell range 
WorkSheet ["Starting Cell Address : Ending Cell Address"].Max()
'to find the Max in specific cell range 
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'WorkSheet ["Starting Cell Address : Ending Cell Address"].Max()
VB   C#

Más información sobre el trabajo con funciones agregadas en Excel para C# y aprenda más sobre cómo extraer datos con distintos métodos.

Veamos un ejemplo de cómo importar datos de archivos Excel aplicando estas funciones.

/**
Import Data by Aggregate Function
anchor-import-excel-data-by-aggregate-functions
**/
using IronXL;
static void Main(string [] args)
{
    //Import Excel file
    WorkBook wb = WorkBook.Load("sample.xlsx");
    //Specify WorkSheet
    WorkSheet ws = wb.GetWorkSheet("Sheet1");
    //Import Excel file data by applying aggregate functions
    decimal Sum = ws ["D2:D9"].Sum();
    decimal Avg = ws ["D2:D9"].Avg();
    decimal Min = ws ["D2:D9"].Min();
    decimal Max = ws ["D2:D9"].Max();
    Console.WriteLine("Sum From D2 To D9: {0}", Sum);
    Console.WriteLine("Avg From D2 To D9: {0}", Avg);
    Console.WriteLine("Min From D2 To D9: {0}", Min);
    Console.WriteLine("Max From D2 To D9: {0}", Max);
    Console.ReadKey();
}
/**
Import Data by Aggregate Function
anchor-import-excel-data-by-aggregate-functions
**/
using IronXL;
static void Main(string [] args)
{
    //Import Excel file
    WorkBook wb = WorkBook.Load("sample.xlsx");
    //Specify WorkSheet
    WorkSheet ws = wb.GetWorkSheet("Sheet1");
    //Import Excel file data by applying aggregate functions
    decimal Sum = ws ["D2:D9"].Sum();
    decimal Avg = ws ["D2:D9"].Avg();
    decimal Min = ws ["D2:D9"].Min();
    decimal Max = ws ["D2:D9"].Max();
    Console.WriteLine("Sum From D2 To D9: {0}", Sum);
    Console.WriteLine("Avg From D2 To D9: {0}", Avg);
    Console.WriteLine("Min From D2 To D9: {0}", Min);
    Console.WriteLine("Max From D2 To D9: {0}", Max);
    Console.ReadKey();
}
'''
'''Import Data by Aggregate Function
'''anchor-import-excel-data-by-aggregate-functions
'''*
Imports IronXL
Shared Sub Main(ByVal args() As String)
	'Import Excel file
	Dim wb As WorkBook = WorkBook.Load("sample.xlsx")
	'Specify WorkSheet
	Dim ws As WorkSheet = wb.GetWorkSheet("Sheet1")
	'Import Excel file data by applying aggregate functions
	Dim Sum As Decimal = ws ("D2:D9").Sum()
	Dim Avg As Decimal = ws ("D2:D9").Avg()
	Dim Min As Decimal = ws ("D2:D9").Min()
	Dim Max As Decimal = ws ("D2:D9").Max()
	Console.WriteLine("Sum From D2 To D9: {0}", Sum)
	Console.WriteLine("Avg From D2 To D9: {0}", Avg)
	Console.WriteLine("Min From D2 To D9: {0}", Min)
	Console.WriteLine("Max From D2 To D9: {0}", Max)
	Console.ReadKey()
End Sub
VB   C#

El código anterior nos da este resultado:

Y nuestro fichero sample.xlsx tendrá estos valores:


6. Importar datos completos de archivos Excel

Si queremos importar datos completos de un archivo Excel en nuestro proyecto CSharp, entonces podemos primero parsear nuestro WorkBook cargado en un DataSet. De este modo, los datos completos de Excel se importarían en el DataSet, y las WorkSheets de los archivos Excel se convertirían en DataTables de ese DataSet. Aquí está en acción:

//import WorkBook into dataset
DataSet ds = WorkBook.ToDataSet();
//import WorkBook into dataset
DataSet ds = WorkBook.ToDataSet();
'import WorkBook into dataset
Dim ds As DataSet = WorkBook.ToDataSet()
VB   C#

De este modo, nuestra WorkSheet especificada se importará en un DataSet que podremos utilizar según nuestras necesidades.

A menudo, la primera columna de un archivo Excel se utiliza como ColumnName. En este caso, tenemos que hacer la primera columna como DataTable ColumnName. Para ello, establecemos el parámetro booleano de ToDataSet() función de IronXL de la siguiente manera:

ToDataSet(true);
ToDataSet(true);
ToDataSet(True)
VB   C#

Esto hará que la primera columna del archivo de Excel como un ColumnName DataTable.

Veamos un ejemplo completo de cómo importar datos de Excel a un Dataset, y utilizar la primera columna de un Excel WorkSheets como ColumnName de DataTable:

/**
Import to Dataset
anchor-import-complete-excel-file-data
**/
using IronXL;
static void Main(string [] args)
{
    WorkBook wb = WorkBook.Load("sample.xlsx");
    WorkSheet ws = wb.GetWorkSheet("Sheet1");
    DataSet ds = new DataSet();
    ds = wb.ToDataSet(true);
    Console.WriteLine("Excel file data imported to dataset successfully.");
    Console.ReadKey();
}
/**
Import to Dataset
anchor-import-complete-excel-file-data
**/
using IronXL;
static void Main(string [] args)
{
    WorkBook wb = WorkBook.Load("sample.xlsx");
    WorkSheet ws = wb.GetWorkSheet("Sheet1");
    DataSet ds = new DataSet();
    ds = wb.ToDataSet(true);
    Console.WriteLine("Excel file data imported to dataset successfully.");
    Console.ReadKey();
}
'''
'''Import to Dataset
'''anchor-import-complete-excel-file-data
'''*
Imports IronXL
Shared Sub Main(ByVal args() As String)
	Dim wb As WorkBook = WorkBook.Load("sample.xlsx")
	Dim ws As WorkSheet = wb.GetWorkSheet("Sheet1")
	Dim ds As New DataSet()
	ds = wb.ToDataSet(True)
	Console.WriteLine("Excel file data imported to dataset successfully.")
	Console.ReadKey()
End Sub
VB   C#

Trabajar con Conjunto de datos y tabla de datos de Excel pueden ser complicadas, pero disponemos de más ejemplos para incorporar datos de archivos a su proyecto C#.


Acceso rápido a la biblioteca

Explorar la referencia IronXL

Obtenga más información sobre cómo extraer datos de Excel a través de celdas, rangos, conjuntos de datos y tablas de datos en nuestra documentación completa Referencia de la API para IronXl.

Explorar la referencia IronXL