- Dependencias de Maven para Apache POI
Para trabajar con archivos Excel en Java, se requiere la biblioteca Apache POI. Añada las siguientes dependencias en el archivo pom.xml:
<properties>
<poi.version>3.14</poi.version>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>${poi.version}</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>${poi.version}</version>
</dependency>
</dependencies>
- Carga de un archivo Excel desde recursos
Para acceder a un archivo Excel almacenado en el directorio de recursos del proyecto, se puede usar el cargador de clases. Ejemplo de lectura inicial:
String rutaArchivo = "plantillas/datos.xlsx";
InputStream flujoEntrada = getClass().getClassLoader().getResourceAsStream(rutaArchivo);
if (flujoEntrada == null) {
System.err.println("No se encontró el archivo: " + rutaArchivo);
}
XSSFWorkbook libro = new XSSFWorkbook(flujoEntrada);
XSSFSheet hoja = libro.getSheetAt(0);
XSSFRow fila = hoja.getRow(0); // Acceso a la primera fila
- Lectura de celdas con manejo de tipos
Al extraer valores de celdas, es crucial manejar los tipos de datos para evitar excepciones. Un método robusto podría ser:
int indiceFila = 1;
XSSFRow filaActual = hoja.getRow(indiceFila);
if (filaActual == null) return;
int totalCeldas = filaActual.getLastCellNum();
for (int col = 0; col < totalCeldas; col++) {
XSSFCell celda = filaActual.getCell(col, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
int tipoCelda = celda.getCellType();
String valorCelda;
if (tipoCelda == Cell.CELL_TYPE_NUMERIC) {
valorCelda = String.valueOf(celda.getNumericCellValue());
} else {
valorCelda = celda.getStringCellValue();
}
System.out.println("Celda [" + col + "]: " + valorCelda);
}
- Ejemplo completo de modificación y escriturra
Este ejemplo muestra cómo leer un archivo Excel, agregar una columna con datos y guardar el resultado. Se han modificado las variables y la lógica interna:
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import java.io.FileOutputStream;
import java.io.InputStream;
public class ProcesadorExcel {
public void ejecutarProceso() throws Exception {
String nombreArchivo = "plantillas/reporte.xlsx";
InputStream is = getClass().getClassLoader().getResourceAsStream(nombreArchivo);
XSSFWorkbook wb = new XSSFWorkbook(is);
XSSFSheet sheet = wb.getSheetAt(0);
XSSFRow primeraFila = sheet.getRow(0);
// Agregar una nueva columna al final
int nuevaColumna = primeraFila.getLastCellNum();
primeraFila.createCell(nuevaColumna).setCellValue("Observaciones");
// Modificar filas adicionales
for (int i = 1; i <= 3; i++) {
XSSFRow fila = sheet.getRow(i);
if (fila != null) {
fila.createCell(nuevaColumna).setCellValue("Procesado fila " + (i + 1));
}
}
// Guardar el archivo modificado
try (FileOutputStream salida = new FileOutputStream("resultado.xlsx")) {
wb.write(salida);
}
wb.close();
}
}
- Aplicación de estilos a celdas
Apache POI permite personalizar el formato de las celdas, como alineación, bordes y colores. A continuación, se detallan ejemplos.
Configuración de alineación
Workbook libro = new HSSFWorkbook();
Sheet hojaEstilos = libro.createSheet("Ejemplo");
Row fila = hojaEstilos.createRow(0);
fila.setHeightInPoints(25);
// Función auxiliar para crear celdas con estilos
private static void configurarAlineacion(Workbook libro, Row fila, int columna, short alineH, short alineV) {
Cell celda = fila.createCell(columna);
celda.setCellValue("Texto de ejemplo");
CellStyle estilo = libro.createCellStyle();
estilo.setAlignment(alineH);
estilo.setVerticalAlignment(alineV);
celda.setCellStyle(estilo);
}
// Uso: configurarAlineacion(libro, fila, 0, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_BOTTOM);
Dfeinición de bordes
Workbook wb = new HSSFWorkbook();
Sheet hoja = wb.createSheet("Bordes");
Row fila = hoja.createRow(0);
Cell celda = fila.createCell(0);
celda.setCellValue(100);
CellStyle estiloBorde = wb.createCellStyle();
estiloBorde.setBorderBottom(CellStyle.BORDER_THIN);
estiloBorde.setBottomBorderColor(IndexedColors.DARK_BLUE.getIndex());
estiloBorde.setBorderLeft(CellStyle.BORDER_DASHED);
estiloBorde.setLeftBorderColor(IndexedColors.GREEN.getIndex());
estiloBorde.setBorderRight(CellStyle.BORDER_MEDIUM);
estiloBorde.setRightBorderColor(IndexedColors.ORANGE.getIndex());
estiloBorde.setBorderTop(CellStyle.BORDER_THICK);
estiloBorde.setTopBorderColor(IndexedColors.RED.getIndex());
celda.setCellStyle(estiloBorde);
Aplicación de colores
Workbook wb = new HSSFWorkbook();
Sheet hoja = wb.createSheet("Colores");
Row fila = hoja.createRow(0);
Cell celdaFondo = fila.createCell(0);
celdaFondo.setCellValue("Fondo con color");
CellStyle estiloFondo = wb.createCellStyle();
estiloFondo.setFillBackgroundColor(IndexedColors.LIGHT_CORNFLOWER_BLUE.getIndex());
estiloFondo.setFillPattern(CellStyle.BIG_SPOTS);
celdaFondo.setCellStyle(estiloFondo);
Cell celdaFrente = fila.createCell(1);
celdaFrente.setCellValue("Color de frente");
CellStyle estiloFrente = wb.createCellStyle();
estiloFrente.setFillForegroundColor(IndexedColors.BRIGHT_GREEN.getIndex());
estiloFrente.setFillPattern(CellStyle.SOLID_FOREGROUND);
celdaFrente.setCellStyle(estiloFrente);
Combinación de celdas
Workbook wb = new HSSFWorkbook();
Sheet hoja = wb.createSheet("Combinadas");
Row fila = hoja.createRow(0);
Cell celda = fila.createCell(0);
celda.setCellValue("Contenido combinado");
// Combinar un rango de celdas
hoja.addMergedRegion(new CellRangeAddress(
0, // Fila inicio
1, // Fila fin
0, // Columna inicio
2 // Columna fin
));