C# Leer archivo XLSX

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

Cuando se trabaja con diversos formatos de Excel, a menudo es necesario leer los datos y manipularlos mediante programación. En el siguiente tutorial, aprenderemos a leer datos de una hoja de cálculo Excel en C# utilizando una práctica herramienta, IronXL.


Primer paso

1. Consiga IronXL para su proyecto

Utilice IronXL en su proyecto para trabajar de forma sencilla con formatos de archivo Excel en C#. Puede instalar IronXL mediante descarga directa o también puede utilizar Instalación de NuGet para Visual Studio. El software es gratuito para el desarrollo.

Install-Package IronXL.Excel


Tutorial

2. Cargar WorkBook

WorkBook es la clase de IronXL cuyo objeto proporciona acceso completo al archivo Excel y a todas sus funciones. Por ejemplo, si queremos acceder a un fichero Excel, utilizaríamos el código

/**
Load Workbook
anchor-load-workbook
**/
WorkBook wb = WorkBook.Load("sample.xlsx");//Excel file path
/**
Load Workbook
anchor-load-workbook
**/
WorkBook wb = WorkBook.Load("sample.xlsx");//Excel file path
'''
'''Load Workbook
'''anchor-load-workbook
'''*
Dim wb As WorkBook = WorkBook.Load("sample.xlsx") 'Excel file path
VB   C#

En el código anterior, WorkBook.Load()La funcióncarga sample.xlsx en wb. Se puede realizar cualquier tipo de función en wb accediendo a la Hoja de Trabajo específica de un fichero Excel.


3. Hoja de trabajo específica de acceso

Para acceder a la Hoja de Trabajo específica de un archivo Excel, IronXL provee la clase WorkSheet. Puede utilizarse de varias maneras:

/**
Access Sheet by Name
anchor-access-specific-worksheet
**/
WorkSheet ws = wb.GetWorkSheet("Sheet1"); //by sheet name
/**
Access Sheet by Name
anchor-access-specific-worksheet
**/
WorkSheet ws = wb.GetWorkSheet("Sheet1"); //by sheet name
'''
'''Access Sheet by Name
'''anchor-access-specific-worksheet
'''*
Dim ws As WorkSheet = wb.GetWorkSheet("Sheet1") 'by sheet name
VB   C#

wb` es el WorkBook declarado en la parte anterior.

O

/**
Access Sheet by Index
anchor-access-specific-worksheet
**/
WorkSheet ws = wb.WorkSheets [0]; //by sheet index
/**
Access Sheet by Index
anchor-access-specific-worksheet
**/
WorkSheet ws = wb.WorkSheets [0]; //by sheet index
'''
'''Access Sheet by Index
'''anchor-access-specific-worksheet
'''*
Dim ws As WorkSheet = wb.WorkSheets (0) 'by sheet index
VB   C#

O

WorkSheet ws = wb.DefaultWorkSheet; //for the default sheet: 
WorkSheet ws = wb.DefaultWorkSheet; //for the default sheet: 
Dim ws As WorkSheet = wb.DefaultWorkSheet 'for the default sheet:
VB   C#

O

WorkSheet ws = wb.WorkSheets.First();//for the first sheet:
WorkSheet ws = wb.WorkSheets.First();//for the first sheet:
Dim ws As WorkSheet = wb.WorkSheets.First() 'for the first sheet:
VB   C#

O

WorkSheet ws = wb.WorkSheets.FirstOrDefault();//for the first or default sheet:
WorkSheet ws = wb.WorkSheets.FirstOrDefault();//for the first or default sheet:
Dim ws As WorkSheet = wb.WorkSheets.FirstOrDefault() 'for the first or default sheet:
VB   C#

Después de obtener ExcelSheet ws , puede obtener cualquier tipo de datos de él y realizar todas las funciones de Excel en él.


4. Acceder a los datos de la hoja de trabajo

En este proceso se puede acceder a los datos desde ExcelSheet ws:

string c = ws ["cell address"].ToString(); //for string
Int32 val = ws ["cell address"].Int32Value; //for integer
string c = ws ["cell address"].ToString(); //for string
Int32 val = ws ["cell address"].Int32Value; //for integer
Dim c As String = ws ("cell address").ToString() 'for string
Dim val As Int32 = ws ("cell address").Int32Value 'for integer
VB   C#

También es posible obtener datos de muchas celdas de una columna específica.

foreach (var cell in ws ["A2:A10"])
{
    Console.WriteLine("value is: {0}",  cell.Text);
}
foreach (var cell in ws ["A2:A10"])
{
    Console.WriteLine("value is: {0}",  cell.Text);
}
For Each cell In ws ("A2:A10")
	Console.WriteLine("value is: {0}", cell.Text)
Next cell
VB   C#

Mostrará los valores de la celda A2 a A10.

Aquí se ofrece un ejemplo de código completo de las especificaciones anteriores.

/**
Access WorkSheet Data
anchor-access-data-from-worksheet
**/
using IronXL;
static void Main(string [] args)
{
    WorkBook wb = WorkBook.Load("sample.xlsx");
    WorkSheet ws = wb.GetWorkSheet("Sheet1");
    foreach (var cell in ws ["A2:A10"])
    {
        Console.WriteLine("value is: {0}", cell.Text);
    }
    Console.ReadKey();
}
/**
Access WorkSheet Data
anchor-access-data-from-worksheet
**/
using IronXL;
static void Main(string [] args)
{
    WorkBook wb = WorkBook.Load("sample.xlsx");
    WorkSheet ws = wb.GetWorkSheet("Sheet1");
    foreach (var cell in ws ["A2:A10"])
    {
        Console.WriteLine("value is: {0}", cell.Text);
    }
    Console.ReadKey();
}
'''
'''Access WorkSheet Data
'''anchor-access-data-from-worksheet
'''*
Imports IronXL
Shared Sub Main(ByVal args() As String)
	Dim wb As WorkBook = WorkBook.Load("sample.xlsx")
	Dim ws As WorkSheet = wb.GetWorkSheet("Sheet1")
	For Each cell In ws ("A2:A10")
		Console.WriteLine("value is: {0}", cell.Text)
	Next cell
	Console.ReadKey()
End Sub
VB   C#

Aparecerá el siguiente resultado:

Con el archivo Excel Sample.xlsx :

Podemos ver lo fácil que es utilizar datos de archivos Excel en su proyecto utilizando estas metodologías.


5. Realizar funciones sobre los datos

Es muy sencillo acceder a datos filtrados desde una hoja de cálculo de Excel aplicando funciones de agregación como Suma, Mín o Máx mediante el siguiente código:

decimal sum = ws ["From:To"].Sum();
decimal min = ws ["From:To"].Min();
decimal max = ws ["From:To"].Max();
decimal sum = ws ["From:To"].Sum();
decimal min = ws ["From:To"].Min();
decimal max = ws ["From:To"].Max();
Dim sum As Decimal = ws ("From:To").Sum()
Dim min As Decimal = ws ("From:To").Min()
Dim max As Decimal = ws ("From:To").Max()
VB   C#

Si quieres más detalles, consulta nuestro tutorial en profundidad sobre Cómo Escribir archivos Excel en C con detalles sobre las funciones agregadas.

/**
Sum Min Max Functions
anchor-perform-functions-on-data
**/
using IronXL;
static void Main(string [] args)
{
    WorkBook wb = WorkBook.Load("sample.xlsx");
    WorkSheet ws = wb.GetWorkSheet("Sheet1");
    decimal sum = ws ["G2:G10"].Sum();
    decimal min = ws ["G2:G10"].Min();
    decimal max = ws ["G2:G10"].Max();
    Console.WriteLine("Sum is: {0}", sum);
    Console.WriteLine("Min is: {0}", min);
    Console.WriteLine("Max is: {0}", max);
    Console.ReadKey();
}
/**
Sum Min Max Functions
anchor-perform-functions-on-data
**/
using IronXL;
static void Main(string [] args)
{
    WorkBook wb = WorkBook.Load("sample.xlsx");
    WorkSheet ws = wb.GetWorkSheet("Sheet1");
    decimal sum = ws ["G2:G10"].Sum();
    decimal min = ws ["G2:G10"].Min();
    decimal max = ws ["G2:G10"].Max();
    Console.WriteLine("Sum is: {0}", sum);
    Console.WriteLine("Min is: {0}", min);
    Console.WriteLine("Max is: {0}", max);
    Console.ReadKey();
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

Este código mostrará la siguiente salida:

Y este es el aspecto que tendrá el archivo Excel Sample.xlsx:


6. Leer hoja de Excel como tabla de datos

Usando IronXL, es muy fácil operar con Excel WorkSheet como una DataTable.

DataTable dt=WorkSheet.ToDataTable();
DataTable dt=WorkSheet.ToDataTable();
Dim dt As DataTable=WorkSheet.ToDataTable()
VB   C#

Si queremos utilizar la primera fila de ExcelSheet como ColumnName de DataTable entonces:

DataTable dt=WorkSheet.ToDataTable(True);
DataTable dt=WorkSheet.ToDataTable(True);
Dim dt As DataTable=WorkSheet.ToDataTable([True])
VB   C#

Así, el parámetro booleano de ToDataTable() establece la primera fila como nombres de columna de tu datatable. Por defecto su valor es False.

/**
WorkSheet as DataTable
anchor-read-excel-worksheet-as-datatable
**/
using IronXL;
using System.Data; 
static void Main(string [] args)
{
    WorkBook wb = WorkBook.Load("sample.xlsx");
    WorkSheet ws = wb.GetWorkSheet("Sheet1");
    DataTable dt = ws.ToDataTable(true);//parse sheet1 of sample.xlsx file into datatable
    foreach (DataRow row in dt.Rows) //access rows
    {
        for (int i = 0; i < dt.Columns.Count; i++) //access columns of corresponding row
        {
            Console.Write(row [i]);
        }
    }
}
/**
WorkSheet as DataTable
anchor-read-excel-worksheet-as-datatable
**/
using IronXL;
using System.Data; 
static void Main(string [] args)
{
    WorkBook wb = WorkBook.Load("sample.xlsx");
    WorkSheet ws = wb.GetWorkSheet("Sheet1");
    DataTable dt = ws.ToDataTable(true);//parse sheet1 of sample.xlsx file into datatable
    foreach (DataRow row in dt.Rows) //access rows
    {
        for (int i = 0; i < dt.Columns.Count; i++) //access columns of corresponding row
        {
            Console.Write(row [i]);
        }
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

Utilizando el código anterior, se puede acceder a cada valor de celda de WorkSheet y utilizarlo según sea necesario.


7. Leer fichero Excel como DataSet

IronXL proporciona la función muy simple de cómo utilizar un archivo completo de Excel (Libro de trabajo) como un DataSet.

DataSet ds = WorkBook.ToDataSet();
DataSet ds = WorkBook.ToDataSet();
Dim ds As DataSet = WorkBook.ToDataSet()
VB   C#

WorkBook es su fichero Excel, como podemos ver en el ejemplo de abajo:

En este ejemplo, veremos cómo utilizar un archivo Excel como DataSet.

/**
Excel File as DataSet
anchor-read-excel-file-as-dataset
**/
using IronXL;
using System.Data; 
static void Main(string [] args)
{           
    WorkBook wb = WorkBook.Load("sample.xlsx");
    DataSet ds = wb.ToDataSet(); //Parse WorkBook wb into DataSet
    foreach (DataTable dt in ds.Tables)
    {
        Console.WriteLine(dt.TableName);
    }
}
/**
Excel File as DataSet
anchor-read-excel-file-as-dataset
**/
using IronXL;
using System.Data; 
static void Main(string [] args)
{           
    WorkBook wb = WorkBook.Load("sample.xlsx");
    DataSet ds = wb.ToDataSet(); //Parse WorkBook wb into DataSet
    foreach (DataTable dt in ds.Tables)
    {
        Console.WriteLine(dt.TableName);
    }
}
'''
'''Excel File as DataSet
'''anchor-read-excel-file-as-dataset
'''*
Imports IronXL
Imports System.Data
Shared Sub Main(ByVal args() As String)
	Dim wb As WorkBook = WorkBook.Load("sample.xlsx")
	Dim ds As DataSet = wb.ToDataSet() 'Parse WorkBook wb into DataSet
	For Each dt As DataTable In ds.Tables
		Console.WriteLine(dt.TableName)
	Next dt
End Sub
VB   C#

La salida del código anterior tendrá el siguiente aspecto:

Y el fichero Excel Muestra.xlsx tendrá este aspecto:

En el ejemplo anterior, vemos que podemos analizar fácilmente el archivo de Excel en DataSet y realizarlo con cada WorkSheet del archivo de Excel como DataTable. Profundice en cómo analizar Excel como DataSet aquí con ejemplos de código.

Veamos un ejemplo más de cómo acceder al valor de cada celda de todas las ExcelSheets. Aquí, podemos acceder a cada valor de celda de cada WorkSheet del archivo Excel.

/**
WorkSheet Cell Values
anchor-read-excel-file-as-dataset
**/
using IronXL;
using System.Data; 
static void Main(string [] args)
{ 
WorkBook wb = WorkBook.Load("sample.xlsx");
DataSet ds = wb.ToDataSet();//behave complete Excel file as DataSet
foreach (DataTable dt in ds.Tables)//behave Excel WorkSheet as DataTable. 
{
    foreach (DataRow row in dt.Rows)//corresponding Sheet's Rows
    {
        for (int i = 0; i < dt.Columns.Count; i++)//Sheet columns of corresponding row
        {
            Console.Write(row [i]);
        }
    }
}
}
/**
WorkSheet Cell Values
anchor-read-excel-file-as-dataset
**/
using IronXL;
using System.Data; 
static void Main(string [] args)
{ 
WorkBook wb = WorkBook.Load("sample.xlsx");
DataSet ds = wb.ToDataSet();//behave complete Excel file as DataSet
foreach (DataTable dt in ds.Tables)//behave Excel WorkSheet as DataTable. 
{
    foreach (DataRow row in dt.Rows)//corresponding Sheet's Rows
    {
        for (int i = 0; i < dt.Columns.Count; i++)//Sheet columns of corresponding row
        {
            Console.Write(row [i]);
        }
    }
}
}
'''
'''WorkSheet Cell Values
'''anchor-read-excel-file-as-dataset
'''*
Imports IronXL
Imports System.Data
Shared Sub Main(ByVal args() As String)
Dim wb As WorkBook = WorkBook.Load("sample.xlsx")
Dim ds As DataSet = wb.ToDataSet() 'behave complete Excel file as DataSet
For Each dt As DataTable In ds.Tables 'behave Excel WorkSheet as DataTable.
	For Each row As DataRow In dt.Rows 'corresponding Sheet's Rows
		For i As Integer = 0 To dt.Columns.Count - 1 'Sheet columns of corresponding row
			Console.Write(row (i))
		Next i
	Next row
Next dt
End Sub
VB   C#

Usando el ejemplo anterior, es muy conveniente acceder a cada valor de celda de cada WorkSheet del archivo Excel.

Para más información Leer archivos Excel sin Interop consulta el código aquí.


Acceso rápido a tutoriales

Referencia API para IronXL

Lea más acerca de las características, clases, campos de métodos, espacios de nombres y enums de IronXL en la documentación.

Referencia API para IronXL