Good day, I have a functionality that replaces the text of some cells in an Excel document, so far it works, but I ran into a problem, when they are excel files that have more than one sheet per book, only the first one runs through the first sheet and replaces, the other leaves do not cover them or anything, if they could help me, I've been looking but only appears to go through a sheet, but they do not say how to make it go through a specific or something like that.
The code that runs through the xlsx file (only the first page) is this:
public static void XLSX(String Ubicacion) throws IOException {
Ubicacion = Ubicacion.replace("\", "/"); //Convierto todos los \ en / para congruir en direcciones
try {
File Fil = new File(Ubicacion); //Se crea un archivo File
FileInputStream file = new FileInputStream(Fil); //Se crea archivo FileInput para la lectura
// Crear el objeto que tendra el libro de Excel
XSSFWorkbook workbook = new XSSFWorkbook(file);
/*
* Obtenemos la primera pestaña a la que se quiera procesar indicando el indice.
* Una vez obtenida la hoja excel con las filas que se quieren leer obtenemos el iterator
* que nos permite recorrer cada una de las filas que contiene.
*/
XSSFSheet sheet = workbook.getSheetAt(0);
Iterator<Row> rowIterator = sheet.iterator();
Row row;
// Recorremos todas las filas para mostrar el contenido de cada celda
while (rowIterator.hasNext()) {
row = rowIterator.next();
// Obtenemos el iterator que permite recorres todas las celdas de una fila
Iterator<Cell> cellIterator = row.cellIterator();
Cell celda;
while (cellIterator.hasNext()) {
celda = cellIterator.next();
// Dependiendo del formato de la celda el valor se debe mostrar como String, Fecha, boolean, entero...
switch (celda.getCellType()) {
case Cell.CELL_TYPE_NUMERIC:
if (DateUtil.isCellDateFormatted(celda)) {
// System.out.println(celda.getDateCellValue());
} else {
//System.out.println(celda.getNumericCellValue());
}
break;
case Cell.CELL_TYPE_STRING:
String item = "";
item = celda.getStringCellValue(); //Tomamos el valor de la celda
if (item.startsWith("<") && item.endsWith(">")) { //validamos que el contenido de la celda comience por < y termine en >
item = item.toLowerCase(); //Hago todo el item en minuscula
item = item.replace(">", "");
item = item.replace("<", "");
System.out.println("ITEM: "+item);
Merge(celda, item); //enviamos donde se le cambiará el item por el valor
}
break;
case Cell.CELL_TYPE_BOOLEAN:
System.out.println(celda.getBooleanCellValue());
break;
}
}
}
// cerramos el libro excel
file.close();
//Se genera el nuevo archivo con los datos cambiados
NewDocumento = "A01_" + "MergeFULL_" + document1 + "_SASPRUEBA_XLSX" + type1; //Creamos el nombre del documento
NewDocumento = ruta1 + NewDocumento; //Agregamos el nombre del documento a la ruta donde se almacena
FileOutputStream fileOut = new FileOutputStream(NewDocumento); //Doy la ruta y el nombre del archivo nuevo que se generará
workbook.write(fileOut); //Escribo el nuevo archivo
fileOut.close(); //Cierro el archivo
} catch (Exception ex) {
System.out.println("ERROR: " + ex);
}
}
The Merge Method is where I do the content replacement where I find the items I need:
public static void Merge(Cell cell, String item) {
if (item.equals("item1")) {
cell.setCellType(Cell.CELL_TYPE_STRING);
cell.setCellValue("Fabian Montoya");
} else if (item.equals("item3")) {
cell.setCellType(Cell.CELL_TYPE_STRING);
cell.setCellValue("Excel_GO");
} else {
cell.setCellType(Cell.CELL_TYPE_STRING);
cell.setCellValue("Item_not_found");
}
}
But as I tell you, it only goes through the first page, in documents with more pages it does not go through them, it only does it in the first one, if you could please help me I would thank you very much.
Libraries, I use POIs
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;