Saltar al pie de página
HERRAMIENTAS DE EXCEL

Cómo leer un archivo de Excel en Java (Tutorial)

¿Qué es Excel?

El libro de trabajo de Microsoft Excel es un software basado en hojas de cálculo que permite a sus usuarios organizar y almacenar datos de manera eficiente. Almacena y organiza los datos en forma de tabla, es decir, usando filas y columnas. La celda en una hoja de cálculo de Excel es el cuadro que contiene datos y se puede manipular con diferentes estilos, formatos y fórmulas.

¿Cómo leer archivos de Excel en Java?

Leer un archivo de Excel puede ser complicado a veces. Leer archivos de Excel en Java también es un poco diferente de leer archivos de Word en Java debido a las celdas de Excel. El JDK no proporciona una API directa para leer o escribir documentos de Microsoft Excel. En su lugar, tenemos que depender de la biblioteca de terceros Apache POI.

Biblioteca Apache POI

POI significa "Poor Obfuscation Implementation". Apache POI es una biblioteca Java de código abierto diseñada para la lectura y escritura de documentos de Microsoft. Ofrece una forma de crear y manipular varios formatos de archivos basados en Microsoft Office. Usando Apache POI, uno debería poder crear, modificar y mostrar/leer operaciones en una gama de formatos de archivos de Microsoft Office.

Descargue e instale la biblioteca Apache POI

Para comenzar, descargaremos la última versión de los JAR de POI. Navegue a http://poi.apache.org/download.html y descargue el archivo ZIP más reciente, que contendrá la API de Java para leer un archivo de Excel en Java.

How to Read Excel Files in Java, Figure 1: Download Binary Distribution File

Descargar archivos JAR de Apache POI

Cuando descargue el archivo ZIP, debe descomprimirlo y agregar los siguientes archivos JAR al classpath de su proyecto. Esto se explica en Leyendo un archivo de Excel a continuación.

How to Read Excel Files in Java, Figure 2: JAR Files

Agregue los archivos Jar de Apache POI a la ruta de clases de Java

Nota: También copie los archivos de lib y ooxml-lib junto con los otros archivos.

Clases e interfaces en POI

Las siguientes son las clases compatibles con el formato de archivo XLS y XLSX que se pueden usar:

How to Read Excel Files in Java, Figure 3: Clases de POI de Apache

Clases de POI de Apache

La siguiente es una lista de diferentes interfaces y clases Java en POI para leer archivos XLS y XLSX en Java:

La interfaz Workbook es implementada por las clases HSSFWorkbook y XSSFWorkbook:

  • HSSFWorkbook: Esta es una representación de clase del archivo XLS.
  • XSSFWorkbook: Esta es una representación de clase del archivo XLSX.

La interfaz Sheet es implementada por las clases HSSFSheet y XSSFSheet:

  • HSSFSheet: Esta es una clase que representa una hoja en un archivo XLS.
  • XSSFSheet: Esta es una clase que representa una hoja en un archivo XLSX.

La interfaz Row es implementada por las clases HSSFRow y XSSFRow:

  • HSSFRow: Esta es una clase que representa una fila en la hoja de un archivo XLS.
  • XSSFRow: Esta es una clase que representa una fila en la hoja de un archivo XLSX.

La interfaz Cell es implementada por las clases HSSFCell y XSSFCell:

  • HSSFCell: Esta es una clase que representa una celda en una fila de un archivo XLS.
  • XSSFCell: Esta es una clase que representa una celda en una fila de un archivo XLSX.

Lectura de un archivo de Excel

Para nuestro ejemplo, leeremos el siguiente archivo Excel en Java:

How to Read Excel Files in Java, Figure 4: The Excel File to be Read

El archivo Excel que se leerá

Pasos para leer un archivo de Excel en Java

  1. Cree un proyecto Java utilizando cualquier IDE de Java. Usaremos Netbeans para este proyecto.
  2. Luego, cree una carpeta lib en el proyecto.
  3. Después, agregue los archivos JAR descargados a la carpeta lib creada en el paso anterior.
  4. Configure el Class-Path haciendo clic derecho en la carpeta del proyecto > Build Path > Add External JARs files > seleccione todos los archivos JAR anteriores > Aplicar y cerrar.
  5. Ahora, creemos un archivo de clase con el nombre ReadExcelFileDemo.
  6. Cree un archivo de Excel con el nombre "studentdata.xls" y escriba los datos anteriores o cualquier dato en él.

A continuación se muestra un ejemplo de código para leer archivos de Excel en Java:

import java.io.File;  
import java.io.FileInputStream;  
import java.io.IOException;  
import org.apache.poi.hssf.usermodel.HSSFSheet;  
import org.apache.poi.hssf.usermodel.HSSFWorkbook;  
import org.apache.poi.ss.usermodel.Cell;  
import org.apache.poi.ss.usermodel.FormulaEvaluator;  
import org.apache.poi.ss.usermodel.Row;  

public class ReadExcelFileDemo  {  
    public static void main(String[] args) throws IOException {  
        // Obtain input bytes from a file  
        FileInputStream fis = new FileInputStream(new File("C:\\demo\\studentdata.xls"));  

        // Creating workbook instance that refers to .xls file  
        HSSFWorkbook wb = new HSSFWorkbook(fis);   

        // Creating a Sheet object to retrieve the object  
        HSSFSheet sheet = wb.getSheetAt(0);  

        // Evaluating cell type   
        FormulaEvaluator formulaEvaluator = wb.getCreationHelper().createFormulaEvaluator();  
        for (Row row : sheet) {  
            for (Cell cell : row) {
                switch (formulaEvaluator.evaluateInCell(cell).getCellType()) {  
                    case NUMERIC: // Field that represents numeric cell type  
                        // Getting the value of the cell as a number  
                        System.out.print(cell.getNumericCellValue() + "\t\t");   
                        break;  
                    case STRING: // Field that represents string cell type  
                        // Getting the value of the cell as a string  
                        System.out.print(cell.getStringCellValue() + "\t\t");  
                        break;
                }
            }
            System.out.println();  
        }

        // Closing the workbook to free resources
        wb.close();
    }
}
import java.io.File;  
import java.io.FileInputStream;  
import java.io.IOException;  
import org.apache.poi.hssf.usermodel.HSSFSheet;  
import org.apache.poi.hssf.usermodel.HSSFWorkbook;  
import org.apache.poi.ss.usermodel.Cell;  
import org.apache.poi.ss.usermodel.FormulaEvaluator;  
import org.apache.poi.ss.usermodel.Row;  

public class ReadExcelFileDemo  {  
    public static void main(String[] args) throws IOException {  
        // Obtain input bytes from a file  
        FileInputStream fis = new FileInputStream(new File("C:\\demo\\studentdata.xls"));  

        // Creating workbook instance that refers to .xls file  
        HSSFWorkbook wb = new HSSFWorkbook(fis);   

        // Creating a Sheet object to retrieve the object  
        HSSFSheet sheet = wb.getSheetAt(0);  

        // Evaluating cell type   
        FormulaEvaluator formulaEvaluator = wb.getCreationHelper().createFormulaEvaluator();  
        for (Row row : sheet) {  
            for (Cell cell : row) {
                switch (formulaEvaluator.evaluateInCell(cell).getCellType()) {  
                    case NUMERIC: // Field that represents numeric cell type  
                        // Getting the value of the cell as a number  
                        System.out.print(cell.getNumericCellValue() + "\t\t");   
                        break;  
                    case STRING: // Field that represents string cell type  
                        // Getting the value of the cell as a string  
                        System.out.print(cell.getStringCellValue() + "\t\t");  
                        break;
                }
            }
            System.out.println();  
        }

        // Closing the workbook to free resources
        wb.close();
    }
}
JAVA

Output:

Id    Names
1     Zeeshan
2     Shoaib
3     Umar
4     Rizwan
5     Ahsan
Id    Names
1     Zeeshan
2     Shoaib
3     Umar
4     Rizwan
5     Ahsan
SHELL

Los pasos son los mismos para leer archivos XLSX, excepto por los siguientes dos puntos principales:

  • Primero, cambia el formato del archivo a .xlsx. El mismo archivo "studentdata" puede usarse, pero con la extensión .xlsx.
  • En segundo lugar, hay una diferencia en cómo importamos Java Apache POI. El código es el siguiente:
import java.io.File;  
import java.io.FileInputStream;  
import java.util.Iterator;  
import org.apache.poi.ss.usermodel.Cell;  
import org.apache.poi.ss.usermodel.Row;  
import org.apache.poi.xssf.usermodel.XSSFSheet;  
import org.apache.poi.xssf.usermodel.XSSFWorkbook;  

public class XLSXReaderExample  {

    public static void main(String[] args) {  
        try {  
            File file = new File("C:\\demo\\studentdata.xlsx");  
            FileInputStream fis = new FileInputStream(file);  

            // Creating Workbook instance that refers to .xlsx file  
            XSSFWorkbook wb = new XSSFWorkbook(fis);   
            XSSFSheet sheet = wb.getSheetAt(0); 

            // Iterating over rows using iterator
            Iterator<Row> itr = sheet.iterator();
            while (itr.hasNext()) {  
                Row row = itr.next();  

                // Iterating over each column in a row
                Iterator<Cell> cellIterator = row.cellIterator();   
                while (cellIterator.hasNext()) {  
                    Cell cell = cellIterator.next();  
                    switch (cell.getCellType()) {  
                        case NUMERIC: // Field that represents numeric cell type  
                            // Getting the value of the cell as a number  
                            System.out.print(cell.getNumericCellValue() + "\t\t");   
                            break;
                        case STRING: // Field that represents string cell type  
                            // Getting the value of the cell as a string  
                            System.out.print(cell.getStringCellValue() + "\t\t");  
                            break;
                    }
                }
                System.out.println("");  
            }  

            // Closing the workbook to free resources
            wb.close();
        } catch (Exception e) {  
            e.printStackTrace();  
        }
    }
}
import java.io.File;  
import java.io.FileInputStream;  
import java.util.Iterator;  
import org.apache.poi.ss.usermodel.Cell;  
import org.apache.poi.ss.usermodel.Row;  
import org.apache.poi.xssf.usermodel.XSSFSheet;  
import org.apache.poi.xssf.usermodel.XSSFWorkbook;  

public class XLSXReaderExample  {

    public static void main(String[] args) {  
        try {  
            File file = new File("C:\\demo\\studentdata.xlsx");  
            FileInputStream fis = new FileInputStream(file);  

            // Creating Workbook instance that refers to .xlsx file  
            XSSFWorkbook wb = new XSSFWorkbook(fis);   
            XSSFSheet sheet = wb.getSheetAt(0); 

            // Iterating over rows using iterator
            Iterator<Row> itr = sheet.iterator();
            while (itr.hasNext()) {  
                Row row = itr.next();  

                // Iterating over each column in a row
                Iterator<Cell> cellIterator = row.cellIterator();   
                while (cellIterator.hasNext()) {  
                    Cell cell = cellIterator.next();  
                    switch (cell.getCellType()) {  
                        case NUMERIC: // Field that represents numeric cell type  
                            // Getting the value of the cell as a number  
                            System.out.print(cell.getNumericCellValue() + "\t\t");   
                            break;
                        case STRING: // Field that represents string cell type  
                            // Getting the value of the cell as a string  
                            System.out.print(cell.getStringCellValue() + "\t\t");  
                            break;
                    }
                }
                System.out.println("");  
            }  

            // Closing the workbook to free resources
            wb.close();
        } catch (Exception e) {  
            e.printStackTrace();  
        }
    }
}
JAVA

Output:

Id    Names
1     Zeeshan
2     Shoaib
3     Umar
4     Rizwan
5     Ahsan
Id    Names
1     Zeeshan
2     Shoaib
3     Umar
4     Rizwan
5     Ahsan
SHELL

La biblioteca IronXL de C

IronXL es una biblioteca independiente de .NET que facilita la lectura y edición de documentos de Microsoft Excel con C#. No requiere que Microsoft Excel esté instalado, ni depende de Interop.

Usando IronXL, los desarrolladores pueden realizar todos los cálculos relacionados con Excel sin esfuerzo, simplemente escribiendo unas pocas líneas de código y con un rendimiento rápido. Esto podría ser para tareas como sumar dos celdas, calcular el total general de una columna, agregar una columna completa a una tabla de Excel, agregar una fila completa a una tabla de Excel, sumas de columna de una o varias filas, o muchas otras tareas facilitadas a través de las funciones útiles de IronXL.

IronXL soporta completamente .NET Framework, .NET Core, Mobile, Xamarin, Azure Linux y macOS.

Conjunto de características de IronXL

  • Cargar, leer y editar datos de XLS/XLSX/CSV/TSV.
  • Guardar y exportar a XLS/XLSX/CSV/TSV/JSON.
  • Objetos System.Data — trabajar con hojas de cálculo de Excel como objetos System.Data.DataSet y System.Data.DataTable.
  • Fórmulas — funciona con fórmulas de Excel.
  • Ranges — la sintaxis ["A1:B10"] es fácil de usar.
  • Sorting — ordenar filas, columnas y rangos.
  • Styling — estilos visuales, fuente y tamaño de fuente, patrón de fondo, borde, alineación y formatos de número.

A continuación se muestra un ejemplo de código de lectura de un archivo de Excel en C# usando IronXL:

using IronXL;
using System.Linq;

public class ExcelReaderExample
{
    public static void Main(string[] args)
    {
        // Supported spreadsheet formats for reading include: XLSX, XLS, CSV and TSV
        WorkBook workbook = WorkBook.Load("test.xlsx");
        WorkSheet sheet = workbook.WorkSheets.First();

        // Select cells easily in Excel notation and return the calculated value
        int cellValue = sheet["A2"].IntValue;

        // Read from Ranges of cells elegantly
        foreach (var cell in sheet["A2:A10"]) {
            Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text);
        }
    }
}
using IronXL;
using System.Linq;

public class ExcelReaderExample
{
    public static void Main(string[] args)
    {
        // Supported spreadsheet formats for reading include: XLSX, XLS, CSV and TSV
        WorkBook workbook = WorkBook.Load("test.xlsx");
        WorkSheet sheet = workbook.WorkSheets.First();

        // Select cells easily in Excel notation and return the calculated value
        int cellValue = sheet["A2"].IntValue;

        // Read from Ranges of cells elegantly
        foreach (var cell in sheet["A2:A10"]) {
            Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text);
        }
    }
}
Imports IronXL
Imports System.Linq

Public Class ExcelReaderExample
	Public Shared Sub Main(ByVal args() As String)
		' Supported spreadsheet formats for reading include: XLSX, XLS, CSV and TSV
		Dim workbook As WorkBook = WorkBook.Load("test.xlsx")
		Dim sheet As WorkSheet = workbook.WorkSheets.First()

		' Select cells easily in Excel notation and return the calculated value
		Dim cellValue As Integer = sheet("A2").IntValue

		' Read from Ranges of cells elegantly
		For Each cell In sheet("A2:A10")
			Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text)
		Next cell
	End Sub
End Class
$vbLabelText   $csharpLabel

Trabajar con IronXL facilita mucho el trabajo de un desarrollador. Su código simple y fácil de usar hace que el software sea menos propenso a errores al trabajar con archivos de Excel.

Descarga IronXL y úsalo con tus proyectos hoy.

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