Saltar al pie de página
USANDO IRONXL

Cómo leer un archivo de Excel en C#

This article will discuss how you can read Excel data in C# using IronXL, a lightweight and fast library that is one of the most widely used C# libraries to interact with Excel files.

1. IronXL

IronXL is a C# library that allows developers to easily read, write, and manipulate Excel files without the need for Microsoft Excel to be installed on the machine. It is a powerful tool for working with Excel data or reading Excel files in C# and provides a simple and easy-to-use API for reading and writing Excel files.

1.1. IronXL Features

IronXL is a C# Excel library that provides a wide range of features or Excel functionality for working with Excel data, including:

Load, Write and Read Excel files

IronXL can read, write, and manipulate Excel files in a variety of formats, including XLS, XLSX, CSV, and XML. It also supports reading of password-protected Excel files and other advanced operations.

Creating charts

IronXL provides support for working with Excel charts, allowing developers to create and manipulate charts within Excel files.

Saving and exporting

IronXL provides support for saving and exporting Excel files in different formats.

Supports many formats

IronXL supports various file formats, such as XLS, XLSX, CSV, and XML.

Working with formulas

IronXL provides support for working with Excel formulas, allowing developers to calculate formulas within Excel files.

Cell Styling and many more

IronXL provides support for working with Excel cell styling, allowing developers to format Excel files professionally.

2. Creating a C# Project

This tutorial will create a project using the C# programming language and Visual Studio 2019.

  • Start Visual Studio now.
  • To start a new project, click "Create."
  • Click on the Next button after selecting C# Console Application form template.

How to Read Excel File in C#, Figure 1: Creating a C# Console Application in Visual Studio Creating a C# Console Application in Visual Studio

  • New window will appear, enter the name of the project and hit Next.

How to Read Excel File in C#, Figure 2: Choose a name for the new C# Console Application Project Choose a name for the new C# Console Application Project

  • In the next window, select the C# .NET Framework that is best supported by your project.

How to Read Excel File in C#, Figure 3: For best results, choose the latest available version of the .NET Framework for your C# Console Project For best results, choose the latest available version of the .NET Framework for your C# Console Project

Existing C# projects can also be used. Simply open the project and add the library. The following section will show how to install the Excel library IronXL.

3. Installing the IronXL Excel Library

There are two methods for downloading and installing the IronXL library:

  1. NuGet Package Manager Console
  2. NuGet Package Manager

3.1 NuGet Package Manager Console

  • Navigate to the Package Manager Console to manage NuGet packages. It is normally at the bottom of Visual Studio.

How to Read Excel File in C#, Figure 4: Access the NuGet Package Manager Console by going to **Tools** - **NuGet Package Manager** - **Package Manager Console**

Access the NuGet Package Manager Console by going to Tools > NuGet Package Manager** > Package Manager Console

  • In the Console, type the following command and press Enter.

    Install-Package IronXL.Excel

The IronXL NuGet Package will start to install and after a minute or two, it will be ready to use.

3.2. Install using NuGet Package Manager

The IronXL library may be installed directly using the NuGet Package Manager UI. To install IronXL, go through the following steps:

  • Hover over NuGet Package Manager in the Tools menu bar.

How to Read Excel File in C#, Figure 5: Access the NuGet Package Manager by going to **Tools** - **NuGet Package Manager** - Manage packages for Solution Access the NuGet Package Manager by going to Tools > NuGet Package Manager > Manage packages for Solution...

  • A dropdown list will appear again. Hover on NuGet Package Manager and click on the Manage NuGet Packages for Solution.

How to Read Excel File in C#, Figure 6: From the NuGet Package Manager submenu, click on Manage NuGet Packages for Solution to access the NuGet Package Manager From the NuGet Package Manager submenu, click on Manage NuGet Packages for Solution to access the NuGet Package Manager

  • Click the Install button after selecting IronXL.Excel package. It will automatically install the library.

4. Read Excel Files

IronXL offers the ability to read Excel sheets programmatically without any software. Just create a C# .NET project and with just only few lines of code, you can read Excel files in your console.

4.1. Reading XLSX file

Reading XLSX files in C# is quite easy using IronXL. The below example will discuss how reading a Microsoft Excel workbook using C# is a piece of cake.

This is an example of an XLSX file containing data from the range A1 to D5 for the following example.

How to Read Excel File in C#, Figure 7: The Excel File that will be used in this example The Excel File that will be used in this example

using IronXL;
using System;
using System.Linq;

// Load the workbook from a file
WorkBook workBook = WorkBook.Load("test.xlsx");

// Access the first worksheet in the workbook
WorkSheet workSheet = workBook.WorkSheets[0];

// Print the content of the worksheet to the console
Console.Write(workSheet);
using IronXL;
using System;
using System.Linq;

// Load the workbook from a file
WorkBook workBook = WorkBook.Load("test.xlsx");

// Access the first worksheet in the workbook
WorkSheet workSheet = workBook.WorkSheets[0];

// Print the content of the worksheet to the console
Console.Write(workSheet);
Imports IronXL
Imports System
Imports System.Linq

' Load the workbook from a file
Private workBook As WorkBook = WorkBook.Load("test.xlsx")

' Access the first worksheet in the workbook
Private workSheet As WorkSheet = workBook.WorkSheets(0)

' Print the content of the worksheet to the console
Console.Write(workSheet)
$vbLabelText   $csharpLabel

How to Read Excel File in C#, Figure 8: The output created from the above code example The output created from the above code example

4.2. Reading Multiple Excel files

Using IronXL, you can read multiple Excel workbooks at the same time. In the source code below, multiple Excel files are read.

using IronXL;
using System;
using System.Linq;

// Load the first workbook and access its first worksheet
WorkBook workBook = WorkBook.Load("test.xlsx");
WorkSheet workSheet = workBook.WorkSheets[0];
Console.WriteLine(workSheet);
Console.WriteLine();

// Load the second workbook (CSV format) and access its first worksheet
WorkBook workBook2 = WorkBook.Load("Example2.Sheet0.csv");
WorkSheet workSheet2 = workBook2.WorkSheets[0];
Console.WriteLine(workSheet2);
Console.WriteLine();
using IronXL;
using System;
using System.Linq;

// Load the first workbook and access its first worksheet
WorkBook workBook = WorkBook.Load("test.xlsx");
WorkSheet workSheet = workBook.WorkSheets[0];
Console.WriteLine(workSheet);
Console.WriteLine();

// Load the second workbook (CSV format) and access its first worksheet
WorkBook workBook2 = WorkBook.Load("Example2.Sheet0.csv");
WorkSheet workSheet2 = workBook2.WorkSheets[0];
Console.WriteLine(workSheet2);
Console.WriteLine();
Imports IronXL
Imports System
Imports System.Linq

' Load the first workbook and access its first worksheet
Private workBook As WorkBook = WorkBook.Load("test.xlsx")
Private workSheet As WorkSheet = workBook.WorkSheets(0)
Console.WriteLine(workSheet)
Console.WriteLine()

' Load the second workbook (CSV format) and access its first worksheet
Dim workBook2 As WorkBook = WorkBook.Load("Example2.Sheet0.csv")
Dim workSheet2 As WorkSheet = workBook2.WorkSheets(0)
Console.WriteLine(workSheet2)
Console.WriteLine()
$vbLabelText   $csharpLabel

How to Read Excel File in C#, Figure 9: Outputting the contents of more than one Excel document Outputting the contents of more than one Excel document

4.3. Read multiple worksheets in a single Excel file

IronXL offers another breakthrough feature to read multiple sheets in a single C# .NET program. You can use this feature for side-by-side comparisons. The below example will read multiple Excel sheets.

using IronXL;
using System;

// Load the workbook that contains multiple sheets
WorkBook workBook = WorkBook.Load("multiple.xlsx");

// Access the first worksheet
WorkSheet workSheet = workBook.WorkSheets[0];
Console.WriteLine(workSheet);
Console.WriteLine();

// Access the second worksheet
WorkSheet workSheet1 = workBook.WorkSheets[1];
Console.WriteLine(workSheet1);
Console.WriteLine();
using IronXL;
using System;

// Load the workbook that contains multiple sheets
WorkBook workBook = WorkBook.Load("multiple.xlsx");

// Access the first worksheet
WorkSheet workSheet = workBook.WorkSheets[0];
Console.WriteLine(workSheet);
Console.WriteLine();

// Access the second worksheet
WorkSheet workSheet1 = workBook.WorkSheets[1];
Console.WriteLine(workSheet1);
Console.WriteLine();
Imports IronXL
Imports System

' Load the workbook that contains multiple sheets
Private workBook As WorkBook = WorkBook.Load("multiple.xlsx")

' Access the first worksheet
Private workSheet As WorkSheet = workBook.WorkSheets(0)
Console.WriteLine(workSheet)
Console.WriteLine()

' Access the second worksheet
Dim workSheet1 As WorkSheet = workBook.WorkSheets(1)
Console.WriteLine(workSheet1)
Console.WriteLine()
$vbLabelText   $csharpLabel

How to Read Excel File in C#, Figure 10: Outputting the contents of more than one worksheet in a single Excel File Outputting the contents of more than one worksheet in a single Excel File

5. Conclusion

Reading Excel files in C# can be a difficult task for those new to programming. However, by using a library such as IronXL, the process becomes much simpler and more manageable.

IronXL is a powerful C# Excel library that provides a wide range of features for working with multiple Excel files or multiple worksheets at the same time.

For more information on how to read Excel files using IronXL, please visit the Read Excel Spreadsheets Code Example.

IronXL is free for development purposes but requires a license for commercial use. View the Reading Excel File in C# Tutorial for more code examples and step-by-step instructions on how to create and read Excel files.

Preguntas Frecuentes

¿Cómo puedo leer archivos de Excel en C# sin usar Interop?

Puedes usar IronXL para leer archivos de Excel en C# sin necesidad de tener instalado Microsoft Excel. IronXL proporciona una API simple para interactuar con archivos de Excel, admitiendo varios formatos como XLS, XLSX, CSV y XML.

¿Cuáles son las ventajas de usar IronXL para la manipulación de archivos de Excel en C#?

IronXL ofrece numerosas ventajas, incluyendo la capacidad para leer y escribir archivos de Excel en múltiples formatos, soporte para archivos protegidos con contraseña, creación de gráficos, manejo de fórmulas y estilos de celdas, todo sin necesidad de tener Microsoft Excel en tu máquina.

¿Cómo instalo IronXL en un proyecto C#?

Instala IronXL en tu proyecto C# utilizando la Consola del Administrador de Paquetes NuGet con el comando Install-Package IronXL.Excel o mediante la interfaz de usuario del Administrador de Paquetes NuGet en Visual Studio.

¿Puedo procesar múltiples archivos de Excel a la vez usando IronXL?

Sí, IronXL te permite leer y procesar múltiples archivos de Excel simultáneamente. Cada archivo puede cargarse por separado usando las clases WorkBook y WorkSheet.

¿Cómo leo múltiples hojas de trabajo de un archivo de Excel en C#?

Con IronXL, puedes leer múltiples hojas de trabajo de un solo archivo de Excel usando el método WorkBook.Load y luego acceder a cada hoja con la clase WorkSheet.

¿Es IronXL gratuito para el desarrollo?

IronXL es gratuito para propósitos de desarrollo, pero requiere una licencia comercial para uso en producción o comercial.

¿Cómo puedo leer un archivo XLSX usando IronXL en C#?

Para leer un archivo XLSX con IronXL, carga el archivo usando WorkBook.Load("file.xlsx"), luego accede a la hoja específica que necesitas con la clase WorkSheet para leer sus datos.

¿IronXL admite la lectura de archivos de Excel con fórmulas?

Sí, IronXL admite la lectura de archivos de Excel que contienen fórmulas, permitiéndote interactuar con y manipular las fórmulas programáticamente.

¿Qué formatos de archivo puedo trabajar con usando IronXL?

IronXL admite una variedad de formatos de archivo, incluidos XLS, XLSX, CSV y XML, lo que lo hace versátil para diferentes operaciones de archivos de Excel.

Jordi Bardia
Ingeniero de Software
Jordi es más competente en Python, C# y C++. Cuando no está aprovechando sus habilidades en Iron Software, está programando juegos. Compartiendo responsabilidades para pruebas de productos, desarrollo de productos e investigación, Jordi agrega un valor inmenso a la mejora continua del producto. La experiencia variada lo mantiene ...
Leer más