[ENGLISH VERSION] Java read excel with Apache Poi Java API
En cualquier aplicación o desarrollo suele ser necesario procesar ficheros excel u otro tipo de hojas de cálculo, en este caso nos vamos a centrar en los documentos OLE 2 de Microsoft, y que manipularemos en este caso usando Apache POI – the Java API for Microsoft Documents, que nos proporciona acceso a los diferentes tipos de ficheros de Microsoft que utilizan esta estructura como: Excel, Word o Powerpoint, también hay otros proyectos dentro de esta API para Visio y Publisher por ejemplo, de todos estos el más desarrollado es Excel Workbooks.
Vamos a explicar como crear una hoja excel, como añadir celdas, modificar su contenido y en definitiva manipular los datos según necesitemos, para ello usaremos la librería POI-HSSF and POI-XSSF – Java API To Access Microsoft, donde HSSF es el proyecto POI de implementación total en Java para ficheros excel.
- HSSFWorkbook: Representación de alto nivel de un libro (Workbook) que será nuestra documento excel. Es el primer objeto que construiremos si vamos a leer o escribir una hoja excel.
- HSSFSheet: representación de alto nivel de una hoja excel, podemos elegir la hoja de la excel usando el HSSFWorkBook.
- HSSFRow: representación de celda de una fila de la hoja excel, solo las filas que tienen filas se pueden añadir a la hoja.
- HSSFCell: representación de una celda en una fila de la un hoja de la excel, la utilizaremos para manejar el contenido de la celda.

Ten en cuenta que para utilizar esta librería la tienes que añadir al proyecto con el que estés trabajando, descarga la librería API Apache Poi Java para añadirla, aquí te explico como añadirla a un proyecto en Netbeans, también te puede servir de orientación con otros IDEs ya que se hace de forma similar.
Java escribir excel con Apache Poi Java API
Para los ejemplos de Apache Poi utilizo una clase que llamo JavaPoiUtils donde creo los métodos para el aprendizaje en Java de la lectura y escritura de ficheros excel, en estos ejemplos estoy utilizando el siguiente fichero excel con países, monedas e idiomas:
Este es su contenido:
En este primer ejemplo vamos a leer el fichero excel que pasaremos como parámetro y crearemos una nueva hoja excel donde haremos una copia de la hoja excel leída, es un ejercicio sencillo que nos introduce en la creación de nuestras propias excel desde Java, a continuación el código Xules donde tenéis todas las explicaciones de lo que se hace:
package org.xulescode.poi;
import java.io.*;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
/**
* Utility class, where we will create methods for training read and write excel files,
* with <a href="https://poi.apache.org/">Apache POI</a>, we use
* <a href="https://poi.apache.org/spreadsheet/">POI-HSSF and POI-XSSF - Java API To Access Microsoft</a>
* HSSF is the POI Project's pure Java implementation of the Excel '97(-2007) file.
*
* Clase de utilidades, donde crearemos métodos
* para el aprendizaje de la lectura y escritura de ficheros excel con
* <a href="https://poi.apache.org/">Apache POI</a>, usaremos
* <a href="https://poi.apache.org/spreadsheet/">POI-HSSF and POI-XSSF - Java API To Access Microsoft</a>
* HSSF es el proyecto POI de implementación total en Java para ficheros Excel '97(-2007).
*
* @author Xules You can follow me on my website http://www.codigoxules.org/en
* Puedes seguirme en mi web http://www.codigoxules.org).
*/
public class JavaPoiUtils {
/**
* Explanation of the method by which we read the excel file we pass as
* parameter if exists, and where we copy its content in a new excel spreadsheet
* is also passed as a parameter.
* Método con el que leemos el fichero excel que pasamos como
* parámetro si existe y donde copiamos su contenido en una nueva hoja excel que
* también se pasa como parámetro.
* @param excelFile <code>String</code>
* excel File we are going to read.
* Fichero excel que vamos a leer.
* @param excelNewFile <code>String</code>
* excel File we are going to write.
* Fichero excel en el que vamos a escribir.
*/
public void readWriteExcelFile(File excelFile, File excelNewFile){
InputStream excelStream = null;
OutputStream excelNewOutputStream = null;
try {
excelStream = new FileInputStream(excelFile);
excelNewOutputStream = new FileOutputStream(excelNewFile);
// High level representation of a workbook.
// Representación del más alto nivel de la hoja excel.
HSSFWorkbook hssfWorkbook = new HSSFWorkbook(excelStream);
HSSFWorkbook hssfWorkbookNew = new HSSFWorkbook();
// We chose the sheet is passed as parameter.
// Elegimos la hoja que se pasa por parámetro.
HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(0);
// We create the new sheet we are going to use.
// Creamos la hoja nueva que vamos a utilizar.
HSSFSheet hssfSheetNew = hssfWorkbookNew.createSheet("Copy-Copia");
// An object that allows us to read a row of the excel sheet, and extract from it the cell contents.
// Objeto que nos permite leer un fila de la hoja excel, y de aquí extraer el contenido de las celdas.
HSSFRow hssfRow;
HSSFRow hssfRowNew;
// Initialize the object to read the value of the cell
// Inicializo el objeto que leerá el valor de la celda
HSSFCell cellNew;
// I get the number of rows occupied on the sheet
// Obtengo el número de filas ocupadas en la hoja
int rows = hssfSheet.getLastRowNum();
String cellValue;
// Creating title row (creando unas filas con título)
// ENGLISH TITLE (Titulo en inglés)
hssfRowNew = hssfSheetNew.createRow(1);
cellNew = hssfRowNew.createCell(1);
cellNew.setCellType(HSSFCell.CELL_TYPE_STRING);
cellNew.setCellValue("THIS IS A COPY");
// SPANISH TITLE (Título en español)
hssfRowNew = hssfSheetNew.createRow(3);
cellNew = hssfRowNew.createCell(1);
cellNew.setCellType(HSSFCell.CELL_TYPE_STRING);
cellNew.setCellValue("ESTO ES UNA COPIA");
// For this example we'll loop through the rows getting all the cells to copy them in the new sheet.
// Para este ejemplo vamos a recorrer todas las filas para obtener todas las celdas y copiarlas en la nueva hoja.
for (int r = 0; r < rows; r++) { hssfRow = hssfSheet.getRow(r); if (hssfRow == null){ break; }else{ System.out.print("Row: " + r + " -> ");
// Creamos la columna en la nueva excel
hssfRowNew = hssfSheetNew.createRow(r + 10);
for (int c = 0; c < hssfRow.getLastCellNum(); c++) {
/*
We have those cell types (tenemos estos tipos de celda):
CELL_TYPE_BLANK, CELL_TYPE_NUMERIC, CELL_TYPE_BLANK, CELL_TYPE_FORMULA, CELL_TYPE_BOOLEAN, CELL_TYPE_ERROR
*/
cellValue = hssfRow.getCell(c) == null?"":
(hssfRow.getCell(c).getCellType() == Cell.CELL_TYPE_STRING)?hssfRow.getCell(c).getStringCellValue():
(hssfRow.getCell(c).getCellType() == Cell.CELL_TYPE_NUMERIC)?"" + hssfRow.getCell(c).getNumericCellValue():
(hssfRow.getCell(c).getCellType() == Cell.CELL_TYPE_BOOLEAN)?"" + hssfRow.getCell(c).getBooleanCellValue():
(hssfRow.getCell(c).getCellType() == Cell.CELL_TYPE_BLANK)?"BLANK":
(hssfRow.getCell(c).getCellType() == Cell.CELL_TYPE_FORMULA)?"FORMULA":
(hssfRow.getCell(c).getCellType() == Cell.CELL_TYPE_ERROR)?"ERROR":"";
System.out.print("[Column " + c + ": " + cellValue + "] ");
cellNew = hssfRowNew.createCell(c);
cellNew.setCellType(HSSFCell.CELL_TYPE_STRING);
cellNew.setCellValue(cellValue);
}
System.out.println();
}
}
hssfWorkbookNew.write(excelNewOutputStream);
excelNewOutputStream.close();
System.out.println("Your excel file has been generated!(¡Se ha generado tu hoja excel!");
} catch (FileNotFoundException fileNotFoundException) {
System.out.println("The file not exists (No se encontró el fichero): " + fileNotFoundException);
} catch (IOException ex) {
System.out.println("Error in file procesing (Error al procesar el fichero): " + ex);
} finally {
try {
excelStream.close();
} catch (IOException ex) {
System.out.println("Error in file processing after close it (Error al procesar el fichero después de cerrarlo): " + ex);
}
}
}
/**
* Main method for the tests for the methods of the class <strong>Java
* read excel</strong> and <strong>Java create excel</strong>
* with <a href="https://poi.apache.org/">Apache POI</a>.
*
* Método main para las pruebas para los método de la clase,
* pruebas de <strong>Java leer excel</strong> y <strong>Java crear excel</strong>
* con <a href="https://poi.apache.org/">Apache POI</a>.
* @param args
*/
public static void main(String[] args){
JavaPoiUtils javaPoiUtils = new JavaPoiUtils();
File excelFile = new File("/home/xules/codigoxules/apachepoi/PaisesIdiomasMonedas.xls");
File newExcelFile = new File("/home/xules/codigoxules/apachepoi/PaisesIdiomasMonedasNuevo.xls");
if (!newExcelFile.exists()){
try {
newExcelFile.createNewFile();
} catch (IOException ioe) {
System.out.println("(Error al crear el fichero nuevo)" + ioe);
}
}
javaPoiUtils.readWriteExcelFile(excelFile, newExcelFile);
}
}
El resultado será una nueva hoja excel que tendrá los mismos datos que la original con el nombre PaisesIdiomasMonedasNuevo.xls, y por pantalla la lectura de la hoja excel ya que como puedes ver he mantenido la impresión por pantalla para que te sirva de orientación, por consola obtendrás algo como esto:
Row: 77 -> [Column 0: 481.0] [Column 1: Thailand] [Column 2: Thailand] [Column 3: TH] [Column 4: N] [Column 5: ] [Column 6: f] [Column 7: th_TH] [Column 8: Thai (Thailand)] [Column 9: th] [Column 10: Euro] [Column 11: Euro] [Column 12: EUR] [Column 13: E] Row: 78 -> [Column 0: 487.0] [Column 1: Tunisia] [Column 2: Tunisia] [Column 3: TN] [Column 4: N] [Column 5: ] [Column 6: f] [Column 7: ar_TN] [Column 8: Arabic (Tunisia)] [Column 9: ar] [Column 10: Euro] [Column 11: Euro] [Column 12: EUR] [Column 13: E] Row: 79 -> [Column 0: 488.0] [Column 1: Turkey] [Column 2: Turkey] [Column 3: TR] [Column 4: N] [Column 5: ] [Column 6: f] [Column 7: tr_TR] [Column 8: Turkish (Turkey)] [Column 9: tr] [Column 10: Euro] [Column 11: Euro] [Column 12: EUR] [Column 13: E] Row: 80 -> [Column 0: 492.0] [Column 1: Ukraine] [Column 2: Ukraine] [Column 3: UA] [Column 4: N] [Column 5: ] [Column 6: f] [Column 7: uk_UA] [Column 8: Ukrainian (Ukraine)] [Column 9: uk] [Column 10: Euro] [Column 11: Euro] [Column 12: EUR] [Column 13: E] Row: 81 -> [Column 0: 493.0] [Column 1: United Arab Emirates] [Column 2: United Arab Emirates] [Column 3: AE] [Column 4: N] [Column 5: ] [Column 6: f] [Column 7: ar_AE] [Column 8: Arabic (United Arab Emirates)] [Column 9: ar] [Column 10: Euro] [Column 11: Euro] [Column 12: EUR] [Column 13: E] Row: 82 -> [Column 0: 494.0] [Column 1: United Kingdom] [Column 2: United Kingdom] [Column 3: GB] [Column 4: N] [Column 5: ] [Column 6: f] [Column 7: en_GB] [Column 8: English (United Kingdom)] [Column 9: en] [Column 10: Euro] [Column 11: Euro] [Column 12: EUR] [Column 13: E] Row: 83 -> [Column 0: 270.0] [Column 1: United States] [Column 2: United States of America] [Column 3: US] [Column 4: Y] [Column 5: State] [Column 6: t] [Column 7: en_US] [Column 8: English (USA)] [Column 9: en] [Column 10: US Dollar] [Column 11: US Dollar] [Column 12: USD] [Column 13: $] Row: 84 -> [Column 0: 496.0] [Column 1: Uruguay] [Column 2: Uruguay] [Column 3: UY] [Column 4: N] [Column 5: ] [Column 6: f] [Column 7: es_UY] [Column 8: Spanish (Uruguay)] [Column 9: es] [Column 10: Euro] [Column 11: Euro] [Column 12: EUR] [Column 13: E] Row: 85 -> [Column 0: 499.0] [Column 1: Venezuela] [Column 2: Venezuela] [Column 3: VE] [Column 4: N] [Column 5: ] [Column 6: f] [Column 7: es_VE] [Column 8: Spanish (Venezuela)] [Column 9: es] [Column 10: Euro] [Column 11: Euro] [Column 12: EUR] [Column 13: E] Your excel file has been generated!(¡Se ha generado tu hoja excel! BUILD SUCCESSFUL (total time: 0 seconds)
Java copiar excel en dos hojas con Apache Poi Java API
Para este ejemplo vamos a crear en la nueva excel dos hojas, en la primera copiaremos los datos igual que el ejercicio anterior, en la segunda desplazaremos los resultados a la fila 20 y haremos una introducción pequeña al uso de estilos y fuentes en una celda, las explicaciones las encontrarás en el ejemplo.
package org.xulescode.poi;
import java.io.*;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
/**
* Utility class, where we will create methods for training read and write excel files,
* with <a href="https://poi.apache.org/">Apache POI</a>, we use
* <a href="https://poi.apache.org/spreadsheet/">POI-HSSF and POI-XSSF - Java API To Access Microsoft</a>
* HSSF is the POI Project's pure Java implementation of the Excel '97(-2007) file.
*
* Clase de utilidades, donde crearemos métodos
* para el aprendizaje de la lectura y escritura de ficheros excel con
* <a href="https://poi.apache.org/">Apache POI</a>, usaremos
* <a href="https://poi.apache.org/spreadsheet/">POI-HSSF and POI-XSSF - Java API To Access Microsoft</a>
* HSSF es el proyecto POI de implementación total en Java para ficheros Excel '97(-2007).
*
* @author Xules You can follow me on my website http://www.codigoxules.org/en
* Puedes seguirme en mi web http://www.codigoxules.org).
*/
public class JavaPoiUtils {
/**
* Explicación del método con el que leemos el fichero excel que pasamos como
* parámetro si existe, en este ejemplo mostramos el contenido por la consola.
*
<h3>Example (Ejemplo)</h3>
*
<pre>
* JavaPoiUtils javaPoiUtils = new JavaPoiUtils();
* File excelFile = new File("/home/xules/codigoxules/apachepoi/PaisesIdiomasMonedas.xls");
* javaPoiUtils.readExcelFile(excelFile);
* File newExcelFile = new File("/home/xules/codigoxules/apachepoi/PaisesIdiomasMonedasNuevoxx.xls");
* if (!newExcelFile.exists()){
* try {
* newExcelFile.createNewFile();
* } catch (IOException ioe) {
* System.out.println("(Error al crear el fichero nuevo)" + ioe);
* }
* }
* javaPoiUtils.readWriteExcelFile(excelFile, newExcelFile);
* </pre>
* @param excelFile <code>String</code>
* excel File we are going to read.
* Fichero excel que vamos a leer.
* @param excelNewFile <code>String</code>
* excel File we are going to write.
* Fichero excel en el que vamos a escribir.
*/
public void readWriteExcelFileMoreSheets(File excelFile, File excelNewFile){
InputStream excelStream = null;
OutputStream excelNewOutputStream = null;
try {
excelStream = new FileInputStream(excelFile);
excelNewOutputStream = new FileOutputStream(excelNewFile);
// High level representation of a workbook.
// Representación del más alto nivel de la hoja excel.
HSSFWorkbook hssfWorkbook = new HSSFWorkbook(excelStream);
HSSFWorkbook hssfWorkbookNew = new HSSFWorkbook();
// We chose the sheet is passed as parameter.
// Elegimos la hoja que se pasa por parámetro.
HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(0);
// We create the new sheet we are going to use.
// Creamos la hoja nueva que vamos a utilizar.
HSSFSheet hssfSheetNew = hssfWorkbookNew.createSheet("Copy-Copia");
// We create a new sheet we are going to copy the values too.
// Creamos una nueva hoja excel donde copiaremos también los datos.
HSSFSheet hssfSheetNew2 = hssfWorkbookNew.createSheet("Copy2-Copia2");
// An object that allows us to read a row of the excel sheet, and extract from it the cell contents.
// Objeto que nos permite leer un fila de la hoja excel, y de aquí extraer el contenido de las celdas.
HSSFRow hssfRow;
HSSFRow hssfRowNew; // for hssfSheetNew
HSSFRow hssfRowNew2; // for hssfSheetNew2
// Initialize the object to read the value of the cell
// Inicializo el objeto que leerá el valor de la celda
HSSFCell cellNew;
// I get the number of rows occupied on the sheet
// Obtengo el número de filas ocupadas en la hoja
int rows = hssfSheet.getLastRowNum();
String cellValue;
// Creating title row (creando unas filas con título)
// ENGLISH TITLE (Titulo en inglés)
hssfRowNew = hssfSheetNew.createRow(1);
cellNew = hssfRowNew.createCell(1, HSSFCell.CELL_TYPE_STRING);
cellNew.setCellValue("THIS IS A COPY");
// SPANISH TITLE (Título en español)
hssfRowNew = hssfSheetNew.createRow(3);
cellNew = hssfRowNew.createCell(1, HSSFCell.CELL_TYPE_STRING);
cellNew.setCellValue("ESTO ES UNA COPIA");
hssfRowNew2 = hssfSheetNew2.createRow(1);
cellNew = hssfRowNew2.createCell(5, HSSFCell.CELL_TYPE_STRING);
cellNew.setCellValue("THIS IS THE SECOND COPY (ESTÁ ES LA SEGUNDA COPIA)");
// Style the cell with border, color background and defining the fill pattern.
// Estilo de la celda con borde, color de fondo y patrón usado.
CellStyle style = hssfWorkbookNew.createCellStyle();
style.setBorderBottom(CellStyle.BORDER_THIN);
style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
style.setFillBackgroundColor(IndexedColors.AQUA.getIndex());
style.setFillPattern(CellStyle.BIG_SPOTS);
// Font definition for the cell, font is part of the cell style
// Definición de la fuente (font) para la celda, la fuente forma parte del estilo de la celda.
HSSFFont font = hssfWorkbookNew.createFont();
font.setBold(true);
font.setFontHeightInPoints((short)24);
font.setColor(HSSFColor.ORANGE.index);
style.setFont(font);
cellNew.setCellStyle(style);
// For this example we'll loop through the rows getting all the cells to copy them in the new sheet.
// Para este ejemplo vamos a recorrer todas las filas para obtener todas las celdas y copiarlas en la nueva hoja.
for (Row row: hssfSheet) {
hssfRowNew = hssfSheetNew.createRow(row.getRowNum() + 10);
hssfRowNew2 = hssfSheetNew2.createRow(row.getRowNum() + 20);
for (Cell cell : row) {
cellValue =
(cell.getCellType() == Cell.CELL_TYPE_STRING)?cell.getStringCellValue():
(cell.getCellType() == Cell.CELL_TYPE_NUMERIC)?"" + cell.getNumericCellValue():
(cell.getCellType() == Cell.CELL_TYPE_BOOLEAN)?"" + cell.getBooleanCellValue():
(cell.getCellType() == Cell.CELL_TYPE_BLANK)?"BLANK":
(cell.getCellType() == Cell.CELL_TYPE_FORMULA)?"FORMULA":
(cell.getCellType() == Cell.CELL_TYPE_ERROR)?"ERROR":"";
cellNew = hssfRowNew.createCell(cell.getColumnIndex(), HSSFCell.CELL_TYPE_STRING);
cellNew.setCellValue(cellValue);
cellNew = hssfRowNew2.createCell(cell.getColumnIndex(), HSSFCell.CELL_TYPE_STRING);
cellNew.setCellValue(cellValue);
}
}
hssfWorkbookNew.write(excelNewOutputStream);
excelNewOutputStream.close();
System.out.println("Your excel file has been generated!(¡Se ha generado tu hoja excel!");
} catch (FileNotFoundException fileNotFoundException) {
System.out.println("The file not exists (No se encontró el fichero): " + fileNotFoundException);
} catch (IOException ex) {
System.out.println("Error in file procesing (Error al procesar el fichero): " + ex);
} finally {
try {
excelStream.close();
} catch (IOException ex) {
System.out.println("Error in file processing after close it (Error al procesar el fichero después de cerrarlo): " + ex);
}
}
}
/**
* Main method for the tests for the methods of the class <strong>Java
* read excel</strong> and <strong>Java create excel</strong>
* with <a href="https://poi.apache.org/">Apache POI</a>.
*
* Método main para las pruebas para los método de la clase,
* pruebas de <strong>Java leer excel</strong> y <strong>Java crear excel</strong>
* con <a href="https://poi.apache.org/">Apache POI</a>.
* @param args
*/
public static void main(String[] args){
JavaPoiUtils javaPoiUtils = new JavaPoiUtils();
File excelFile = new File("/home/xules/codigoxules/apachepoi/PaisesIdiomasMonedas.xls");
File newExcelFile = new File("/home/xules/codigoxules/apachepoi/PaisesIdiomasMonedasNuevoDos.xls");
if (!newExcelFile.exists()){
try {
newExcelFile.createNewFile();
} catch (IOException ioe) {
System.out.println("(Error al crear el fichero nuevo)" + ioe);
}
}
javaPoiUtils.readWriteExcelFileMoreSheets(excelFile, newExcelFile);
}
}
El resultado será una nueva hoja excel que tendrá los mismos datos que la original con el nombre PaisesIdiomasMonedasNuevoDos.xls con dos hojas con los nombres: Copy-Copia y Copy2-Copia2, por consola obtendrás simplemente un mensaje de éxito si todo fue bien:
run: Your excel file has been generated!(¡Se ha generado tu hoja excel! BUILD SUCCESSFUL (total time: 0 seconds)
Esta es una imagen de la hoja excel creada:
Si la quieres descargar para echar un vistazo aquí la tienes:
Espero que te haya sido útilXules
Xules
¿Qué hacemos ahora?
A continuación, te dejo para que continúes aprendiendo los enlaces de lectura de hojas excel con Apache POI – the Java API for Microsoft Documents.
Java leer excel con Apache Poi Java API
Vamos a crear la clase de utilidades JavaPoiUtils donde crearemos métodos para el aprendizaje de la lectura y procesamiento de hojas excel en JavaCódigo Xules
Código Xules
Netbeans añadir librería Apache Poi Java API
Descargamos la librería API Apache Poi Java para añadirla a nuestro proyecto, en Netbeans … Código Xules
Código Xules
Java leer ficheros
Usamos la clase java.io.File que nos proporciona una representación abstracta de un fichero o directorio, con métodos para el manejo de ficheros y directorios.Código Xules
Código Xules
In any application or development is often necessary to process Excel files or other spreadsheets, in this case, we will focus on Microsoft’s OLE 2 documents, and manipulate them in this case using Apache POI – the Java API for Microsoft Documents,that provides access to different file types Microsoft that use this structure as Excel, Word or Powerpoint, there are other projects in this API to Visio and Publisher for example all these the more developed Excel Workbooks.
We’ll explain how to create a new excel sheet, how to add cells, modify its content and modify its content and definitely manipulate data according to need using the POI-HSSF and POI-XSSF – Java API To Access Microsoft library, where HSSF is the POI project full implementation in Java for excel.
We will introduce the elements of this library that we will use to read and create an Excel spreadsheet.
- HSSFWorkbook: High level representation of a workbook. This is the first object will construct whether they are reading or writing a workbook.
- HSSFSheet: high level representation of a worksheet, we can choose the sheet using the HSSFWorkBook.
- HSSFRow: representation of a row of a spreadsheet, only rows that have cells should be added to a Sheet.
- HSSFCell: representation of a cell in a row of a spreadsheet, we use to manage the contents of the cell.
Make attention for use this library you need to add it to the project that you are working on, download the library API Apache Poi Java to add it, here I explain how to add it to a Netbeans project, also It can be useful with other IDEs because is do it in a similar way.
Java write excel with Apache Poi Java API
For examples of Apache Poi use a class I call JavaPoiUtils where I create learning methods in Java for reading and writing files excel in these examples I am using excel file with the following countries, currencies and languages:
This is the content:
In this first example where are going to read the excel file that we’ll pass it as a parameter and create a new Excel spreadsheet where we’ll copy the read Excel sheet is a simple exercise that introduces us to create our own Excel from Java, then the Xules code where you have all the explanations of what is done:
package org.xulescode.poi;
import java.io.*;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
/**
* Utility class, where we will create methods for training read and write excel files,
* with <a href="https://poi.apache.org/">Apache POI</a>, we use
* <a href="https://poi.apache.org/spreadsheet/">POI-HSSF and POI-XSSF - Java API To Access Microsoft</a>
* HSSF is the POI Project's pure Java implementation of the Excel '97(-2007) file.
*
* Clase de utilidades, donde crearemos métodos
* para el aprendizaje de la lectura y escritura de ficheros excel con
* <a href="https://poi.apache.org/">Apache POI</a>, usaremos
* <a href="https://poi.apache.org/spreadsheet/">POI-HSSF and POI-XSSF - Java API To Access Microsoft</a>
* HSSF es el proyecto POI de implementación total en Java para ficheros Excel '97(-2007).
*
* @author Xules You can follow me on my website http://www.codigoxules.org/en
* Puedes seguirme en mi web http://www.codigoxules.org).
*/
public class JavaPoiUtils {
/**
* Explanation of the method by which we read the excel file we pass as
* parameter if exists, and where we copy its content in a new excel spreadsheet
* is also passed as a parameter.
* Método con el que leemos el fichero excel que pasamos como
* parámetro si existe y donde copiamos su contenido en una nueva hoja excel que
* también se pasa como parámetro.
* @param excelFile <code>String</code>
* excel File we are going to read.
* Fichero excel que vamos a leer.
* @param excelNewFile <code>String</code>
* excel File we are going to write.
* Fichero excel en el que vamos a escribir.
*/
public void readWriteExcelFile(File excelFile, File excelNewFile){
InputStream excelStream = null;
OutputStream excelNewOutputStream = null;
try {
excelStream = new FileInputStream(excelFile);
excelNewOutputStream = new FileOutputStream(excelNewFile);
// High level representation of a workbook.
// Representación del más alto nivel de la hoja excel.
HSSFWorkbook hssfWorkbook = new HSSFWorkbook(excelStream);
HSSFWorkbook hssfWorkbookNew = new HSSFWorkbook();
// We chose the sheet is passed as parameter.
// Elegimos la hoja que se pasa por parámetro.
HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(0);
// We create the new sheet we are going to use.
// Creamos la hoja nueva que vamos a utilizar.
HSSFSheet hssfSheetNew = hssfWorkbookNew.createSheet("Copy-Copia");
// An object that allows us to read a row of the excel sheet, and extract from it the cell contents.
// Objeto que nos permite leer un fila de la hoja excel, y de aquí extraer el contenido de las celdas.
HSSFRow hssfRow;
HSSFRow hssfRowNew;
// Initialize the object to read the value of the cell
// Inicializo el objeto que leerá el valor de la celda
HSSFCell cellNew;
// I get the number of rows occupied on the sheet
// Obtengo el número de filas ocupadas en la hoja
int rows = hssfSheet.getLastRowNum();
String cellValue;
// Creating title row (creando unas filas con título)
// ENGLISH TITLE (Titulo en inglés)
hssfRowNew = hssfSheetNew.createRow(1);
cellNew = hssfRowNew.createCell(1);
cellNew.setCellType(HSSFCell.CELL_TYPE_STRING);
cellNew.setCellValue("THIS IS A COPY");
// SPANISH TITLE (Título en español)
hssfRowNew = hssfSheetNew.createRow(3);
cellNew = hssfRowNew.createCell(1);
cellNew.setCellType(HSSFCell.CELL_TYPE_STRING);
cellNew.setCellValue("ESTO ES UNA COPIA");
// For this example we'll loop through the rows getting all the cells to copy them in the new sheet.
// Para este ejemplo vamos a recorrer todas las filas para obtener todas las celdas y copiarlas en la nueva hoja.
for (int r = 0; r < rows; r++) {
hssfRow = hssfSheet.getRow(r);
if (hssfRow == null){
break;
}else{
System.out.print("Row: " + r + " -> ");
// Creamos la columna en la nueva excel
hssfRowNew = hssfSheetNew.createRow(r + 10);
for (int c = 0; c < hssfRow.getLastCellNum(); c++) {
/*
We have those cell types (tenemos estos tipos de celda):
CELL_TYPE_BLANK, CELL_TYPE_NUMERIC, CELL_TYPE_BLANK, CELL_TYPE_FORMULA, CELL_TYPE_BOOLEAN, CELL_TYPE_ERROR
*/
cellValue = hssfRow.getCell(c) == null?"":
(hssfRow.getCell(c).getCellType() == Cell.CELL_TYPE_STRING)?hssfRow.getCell(c).getStringCellValue():
(hssfRow.getCell(c).getCellType() == Cell.CELL_TYPE_NUMERIC)?"" + hssfRow.getCell(c).getNumericCellValue():
(hssfRow.getCell(c).getCellType() == Cell.CELL_TYPE_BOOLEAN)?"" + hssfRow.getCell(c).getBooleanCellValue():
(hssfRow.getCell(c).getCellType() == Cell.CELL_TYPE_BLANK)?"BLANK":
(hssfRow.getCell(c).getCellType() == Cell.CELL_TYPE_FORMULA)?"FORMULA":
(hssfRow.getCell(c).getCellType() == Cell.CELL_TYPE_ERROR)?"ERROR":"";
System.out.print("[Column " + c + ": " + cellValue + "] ");
cellNew = hssfRowNew.createCell(c);
cellNew.setCellType(HSSFCell.CELL_TYPE_STRING);
cellNew.setCellValue(cellValue);
}
System.out.println();
}
}
hssfWorkbookNew.write(excelNewOutputStream);
excelNewOutputStream.close();
System.out.println("Your excel file has been generated!(¡Se ha generado tu hoja excel!");
} catch (FileNotFoundException fileNotFoundException) {
System.out.println("The file not exists (No se encontró el fichero): " + fileNotFoundException);
} catch (IOException ex) {
System.out.println("Error in file procesing (Error al procesar el fichero): " + ex);
} finally {
try {
excelStream.close();
} catch (IOException ex) {
System.out.println("Error in file processing after close it (Error al procesar el fichero después de cerrarlo): " + ex);
}
}
}
/**
* Main method for the tests for the methods of the class <strong>Java
* read excel</strong> and <strong>Java create excel</strong>
* with <a href="https://poi.apache.org/">Apache POI</a>.
* <br>
* Método main para las pruebas para los método de la clase,
* pruebas de <strong>Java leer excel</strong> y <strong>Java crear excel</strong>
* con <a href="https://poi.apache.org/">Apache POI</a>.
* @param args
*/
public static void main(String[] args){
JavaPoiUtils javaPoiUtils = new JavaPoiUtils();
File excelFile = new File("/home/xules/codigoxules/apachepoi/PaisesIdiomasMonedas.xls");
File newExcelFile = new File("/home/xules/codigoxules/apachepoi/PaisesIdiomasMonedasNuevo.xls");
if (!newExcelFile.exists()){
try {
newExcelFile.createNewFile();
} catch (IOException ioe) {
System.out.println("(Error al crear el fichero nuevo)" + ioe);
}
}
javaPoiUtils.readWriteExcelFile(excelFile, newExcelFile);
}
}
Java copy excel in two sheets with Apache Poi Java API
For this example we will create in the new excel two sheets, the first will copy the data like the previous exercise, the second will move the results to row 21 and we will add new title making a brief introduction to the use of styles and fonts in a cell, you find explanations of the example.
package org.xulescode.poi;
import java.io.*;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
/**
* Utility class, where we will create methods for training read and write excel files,
* with <a href="https://poi.apache.org/">Apache POI</a>, we use
* <a href="https://poi.apache.org/spreadsheet/">POI-HSSF and POI-XSSF - Java API To Access Microsoft</a>
* HSSF is the POI Project's pure Java implementation of the Excel '97(-2007) file.
*
* Clase de utilidades, donde crearemos métodos
* para el aprendizaje de la lectura y escritura de ficheros excel con
* <a href="https://poi.apache.org/">Apache POI</a>, usaremos
* <a href="https://poi.apache.org/spreadsheet/">POI-HSSF and POI-XSSF - Java API To Access Microsoft</a>
* HSSF es el proyecto POI de implementación total en Java para ficheros Excel '97(-2007).
*
* @author Xules You can follow me on my website http://www.codigoxules.org/en
* Puedes seguirme en mi web http://www.codigoxules.org).
*/
public class JavaPoiUtils {
/**
* Explicación del método con el que leemos el fichero excel que pasamos como
* parámetro si existe, en este ejemplo mostramos el contenido por la consola.
* <h3>Example (Ejemplo)</h3>
* <pre>
* JavaPoiUtils javaPoiUtils = new JavaPoiUtils();
* File excelFile = new File("/home/xules/codigoxules/apachepoi/PaisesIdiomasMonedas.xls");
* javaPoiUtils.readExcelFile(excelFile);
* File newExcelFile = new File("/home/xules/codigoxules/apachepoi/PaisesIdiomasMonedasNuevoxx.xls");
* if (!newExcelFile.exists()){
* try {
* newExcelFile.createNewFile();
* } catch (IOException ioe) {
* System.out.println("(Error al crear el fichero nuevo)" + ioe);
* }
* }
* javaPoiUtils.readWriteExcelFile(excelFile, newExcelFile);
* </pre>
* @param excelFile <code>String</code>
* excel File we are going to read.
* Fichero excel que vamos a leer.
* @param excelNewFile <code>String</code>
* excel File we are going to write.
* Fichero excel en el que vamos a escribir.
*/
public void readWriteExcelFileMoreSheets(File excelFile, File excelNewFile){
InputStream excelStream = null;
OutputStream excelNewOutputStream = null;
try {
excelStream = new FileInputStream(excelFile);
excelNewOutputStream = new FileOutputStream(excelNewFile);
// High level representation of a workbook.
// Representación del más alto nivel de la hoja excel.
HSSFWorkbook hssfWorkbook = new HSSFWorkbook(excelStream);
HSSFWorkbook hssfWorkbookNew = new HSSFWorkbook();
// We chose the sheet is passed as parameter.
// Elegimos la hoja que se pasa por parámetro.
HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(0);
// We create the new sheet we are going to use.
// Creamos la hoja nueva que vamos a utilizar.
HSSFSheet hssfSheetNew = hssfWorkbookNew.createSheet("Copy-Copia");
// We create a new sheet we are going to copy the values too.
// Creamos una nueva hoja excel donde copiaremos también los datos.
HSSFSheet hssfSheetNew2 = hssfWorkbookNew.createSheet("Copy2-Copia2");
// An object that allows us to read a row of the excel sheet, and extract from it the cell contents.
// Objeto que nos permite leer un fila de la hoja excel, y de aquí extraer el contenido de las celdas.
HSSFRow hssfRow;
HSSFRow hssfRowNew; // for hssfSheetNew
HSSFRow hssfRowNew2; // for hssfSheetNew2
// Initialize the object to read the value of the cell
// Inicializo el objeto que leerá el valor de la celda
HSSFCell cellNew;
// I get the number of rows occupied on the sheet
// Obtengo el número de filas ocupadas en la hoja
int rows = hssfSheet.getLastRowNum();
String cellValue;
// Creating title row (creando unas filas con título)
// ENGLISH TITLE (Titulo en inglés)
hssfRowNew = hssfSheetNew.createRow(1);
cellNew = hssfRowNew.createCell(1, HSSFCell.CELL_TYPE_STRING);
cellNew.setCellValue("THIS IS A COPY");
// SPANISH TITLE (Título en español)
hssfRowNew = hssfSheetNew.createRow(3);
cellNew = hssfRowNew.createCell(1, HSSFCell.CELL_TYPE_STRING);
cellNew.setCellValue("ESTO ES UNA COPIA");
hssfRowNew2 = hssfSheetNew2.createRow(1);
cellNew = hssfRowNew2.createCell(5, HSSFCell.CELL_TYPE_STRING);
cellNew.setCellValue("THIS IS THE SECOND COPY (ESTÁ ES LA SEGUNDA COPIA)");
// Style the cell with border, color background and defining the fill pattern.
// Estilo de la celda con borde, color de fondo y patrón usado.
CellStyle style = hssfWorkbookNew.createCellStyle();
style.setBorderBottom(CellStyle.BORDER_THIN);
style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
style.setFillBackgroundColor(IndexedColors.AQUA.getIndex());
style.setFillPattern(CellStyle.BIG_SPOTS);
// Font definition for the cell, font is part of the cell style
// Definición de la fuente (font) para la celda, la fuente forma parte del estilo de la celda.
HSSFFont font = hssfWorkbookNew.createFont();
font.setBold(true);
font.setFontHeightInPoints((short)24);
font.setColor(HSSFColor.ORANGE.index);
style.setFont(font);
cellNew.setCellStyle(style);
// For this example we'll loop through the rows getting all the cells to copy them in the new sheet.
// Para este ejemplo vamos a recorrer todas las filas para obtener todas las celdas y copiarlas en la nueva hoja.
for (Row row: hssfSheet) {
hssfRowNew = hssfSheetNew.createRow(row.getRowNum() + 10);
hssfRowNew2 = hssfSheetNew2.createRow(row.getRowNum() + 20);
for (Cell cell : row) {
cellValue =
(cell.getCellType() == Cell.CELL_TYPE_STRING)?cell.getStringCellValue():
(cell.getCellType() == Cell.CELL_TYPE_NUMERIC)?"" + cell.getNumericCellValue():
(cell.getCellType() == Cell.CELL_TYPE_BOOLEAN)?"" + cell.getBooleanCellValue():
(cell.getCellType() == Cell.CELL_TYPE_BLANK)?"BLANK":
(cell.getCellType() == Cell.CELL_TYPE_FORMULA)?"FORMULA":
(cell.getCellType() == Cell.CELL_TYPE_ERROR)?"ERROR":"";
cellNew = hssfRowNew.createCell(cell.getColumnIndex(), HSSFCell.CELL_TYPE_STRING);
cellNew.setCellValue(cellValue);
cellNew = hssfRowNew2.createCell(cell.getColumnIndex(), HSSFCell.CELL_TYPE_STRING);
cellNew.setCellValue(cellValue);
}
}
hssfWorkbookNew.write(excelNewOutputStream);
excelNewOutputStream.close();
System.out.println("Your excel file has been generated!(¡Se ha generado tu hoja excel!)");
} catch (FileNotFoundException fileNotFoundException) {
System.out.println("The file not exists (No se encontró el fichero): " + fileNotFoundException);
} catch (IOException ex) {
System.out.println("Error in file procesing (Error al procesar el fichero): " + ex);
} finally {
try {
excelStream.close();
} catch (IOException ex) {
System.out.println("Error in file processing after close it (Error al procesar el fichero después de cerrarlo): " + ex);
}
}
}
/**
* Main method for the tests for the methods of the class <strong>Java
* read excel</strong> and <strong>Java create excel</strong>
* with <a href="https://poi.apache.org/">Apache POI</a>.
* <br>
* Método main para las pruebas para los método de la clase,
* pruebas de <strong>Java leer excel</strong> y <strong>Java crear excel</strong>
* con <a href="https://poi.apache.org/">Apache POI</a>.
* @param args
*/
public static void main(String[] args){
JavaPoiUtils javaPoiUtils = new JavaPoiUtils();
File excelFile = new File("/home/xules/codigoxules/apachepoi/PaisesIdiomasMonedas.xls");
File newExcelFile = new File("/home/xules/codigoxules/apachepoi/PaisesIdiomasMonedasNuevoDos.xls");
if (!newExcelFile.exists()){
try {
newExcelFile.createNewFile();
} catch (IOException ioe) {
System.out.println("(Error al crear el fichero nuevo)" + ioe);
}
}
javaPoiUtils.readWriteExcelFileMoreSheets(excelFile, newExcelFile);
}
}
The result will be a new Excel sheet have the same data as the original with the name PaisesIdiomasMonedasNuevoDos.xls with two sheets with the names: Copy-Copia and Copy2-Copia2, via console simply get a success message if all went well:
run: Your excel file has been generated!(¡Se ha generado tu hoja excel!) BUILD SUCCESSFUL (total time: 0 seconds)
This is a picture of created excel sheet:
If you want to download it to have a look here you got it:
I hope it has been usefulXules
Xules
What do we do now?
Then I leave for you to continue learning links reading and writing Excel spreadsheets with Apache POI – the Java API for Microsoft Documents.
Java leer excel con Apache Poi Java API
We will create the class of utilities JavaPoiUtils where we will create methods for learning and reading and sheet processing excel in JavaXules Code
Xules Code
Netbeans add library Apache Poi Java API
Download API Apache Poi Java library to add to our project in Netbeans … Xules Code
Xules Code
Java create file
We use the java.io package, where are most of the classes for managing files.Xules code
Xules code


Hola amigo, probe la lectura desde otro archivo Excel pero no tuvo resultado, eso es por
la estructura en el que se hizo el codigo? o deberia servir para cualquier archivo Excel y yo habre cometido un error?
Hola Sebastián.
El código es válido cualquier cualquier Excel, yo lo he probado con extensiones xls y xlsx, como se indica en la librería de a Apache POI el soporte es para Excel 97 a 2007, con esta lista de utilidades desarrolladas:
Un saludo.
Hola caballero
Espero me puedas hacer el favor de apoyarme
Tengo una celda llena
¿Como hago para pasar a la siguiente desde netbeans?
Ejemplo
Tengo A1 llena como hago para pasar a A2 automaticamente
Hola Manuel.
Esto es lo que estoy haciendo en el código (donde creo un nueva fila y voy añadiendo celdas):
// Para este ejemplo vamos a recorrer todas las filas para obtener todas las celdas y copiarlas en la nueva hoja. for (Row row: hssfSheet) { hssfRowNew = hssfSheetNew.createRow(row.getRowNum() + 10); hssfRowNew2 = hssfSheetNew2.createRow(row.getRowNum() + 20); for (Cell cell : row) { cellValue = (cell.getCellType() == Cell.CELL_TYPE_STRING)?cell.getStringCellValue(): (cell.getCellType() == Cell.CELL_TYPE_NUMERIC)?"" + cell.getNumericCellValue(): (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN)?"" + cell.getBooleanCellValue(): (cell.getCellType() == Cell.CELL_TYPE_BLANK)?"BLANK": (cell.getCellType() == Cell.CELL_TYPE_FORMULA)?"FORMULA": (cell.getCellType() == Cell.CELL_TYPE_ERROR)?"ERROR":""; cellNew = hssfRowNew.createCell(cell.getColumnIndex(), HSSFCell.CELL_TYPE_STRING); cellNew.setCellValue(cellValue); cellNew = hssfRowNew2.createCell(cell.getColumnIndex(), HSSFCell.CELL_TYPE_STRING); cellNew.setCellValue(cellValue); } } hssfWorkbookNew.write(excelNewOutputStream);Utiliza este ejemplo para recorrer las filas e ir rellenando las celdas A1, A2, …
Un saludo.
Espero que te sirva de ayuda.
Muy bueno
Hola Luis.
Muchas gracias por tu valoración, espero que te haya resultado útil.
Un saludo.
Hola, disculpa podrías indicarme ¿Cuáles serían las sentencias para crear una fuente tamaño 14, subrayada y color rojo para ser aplicada en un archivo excel? usando HSSFFont.
Muchas gracias
Hola Erika.
En el ejemplo se explica como hacer esto, solo tienes que cambiar los datos:
// Definición de la fuente (font) para la celda, la fuente forma parte del estilo de la celda.
HSSFFont font = hssfWorkbookNew.createFont();
font.setBold(true);
font.setFontHeightInPoints((short)24);
font.setColor(HSSFColor.ORANGE.index);
style.setFont(font);
cellNew.setCellStyle(style);
Un saludo.
Hola que tal, te agradezco mucho, me amplio mi panorama de todo lo que puedo hacer, sin embargo tengo una duda, el archivo nuevo que trato de abrir , me arroja que esta corrupto y no lo puede abrir, es por mi archivo origen?
Hola Luis.
Con la información que me proporcionas no se decirte exactamente que te esta pasando, no debería ser de tu archivo origen ya que el nuevo archivo se crea desde la aplicación como en el ejemplo.
Gracias por tu valoración
Un saludo.
Buenas noches, ojala puedas apoyarme…
Te comento….pretendo leer un archivo de Excel ya existente y escribir en ese archivo pero… me abre el archivo de excel sin problema…aunque no logro escribir en ninguna celda…y no encuentro el problema..te anexo lo que estoy haciendo:
String nombreArchivo = «MiArchivoExcel.xls»;
String rutaArchivo = «C:\\Documents\\» + nombreArchivo;
try (FileInputStream file = new FileInputStream(new File(rutaArchivo))) {
HSSFWorkbook worbook = new HSSFWorkbook(file);
HSSFSheet sheet = worbook.getSheetAt(0);
HSSFRow Fila = sheet.getRow(2);
HSSFCell cell1 = Fila.getCell(3);
CellStyle styleFont = worbook.createCellStyle();
if (cell1 == null)
cell1 = Fila.createCell(3);
cell1.setCellValue(«Mi Horario»);
como puedo escribir en una celda especifica desde java a excel
En esta parte del código tienes la respuesta:
for (Row row: hssfSheet) { hssfRowNew = hssfSheetNew.createRow(row.getRowNum() + 10); hssfRowNew2 = hssfSheetNew2.createRow(row.getRowNum() + 20); for (Cell cell : row) { cellValue = (cell.getCellType() == Cell.CELL_TYPE_STRING)?cell.getStringCellValue(): (cell.getCellType() == Cell.CELL_TYPE_NUMERIC)?"" + cell.getNumericCellValue(): (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN)?"" + cell.getBooleanCellValue(): (cell.getCellType() == Cell.CELL_TYPE_BLANK)?"BLANK": (cell.getCellType() == Cell.CELL_TYPE_FORMULA)?"FORMULA": (cell.getCellType() == Cell.CELL_TYPE_ERROR)?"ERROR":""; cellNew = hssfRowNew.createCell(cell.getColumnIndex(), HSSFCell.CELL_TYPE_STRING); cellNew.setCellValue(cellValue); cellNew = hssfRowNew2.createCell(cell.getColumnIndex(), HSSFCell.CELL_TYPE_STRING); cellNew.setCellValue(cellValue); } }Para hacer lo que dices tienes que seguir estos pasos: