xssfworkbook write poi ooxml librería descargar create java excel apache-poi

java - write - Combinar y alinear la celda central usando apache poi



write excel java (8)

Quiero exportar datos a Excel usando Apache poi .
Ahora el problema al que me enfrento es que no puedo combinar filas y alinearlas en el centro.

El código para exportar datos es:

List<LinkedHashMap<String,Object>> lstReportHeader = null; HSSFWorkbook wb = new HSSFWorkbook(); HSSFSheet sheet = wb.createSheet(); //Set Header Font HSSFFont headerFont = wb.createFont(); headerFont.setBoldweight(headerFont.BOLDWEIGHT_BOLD); headerFont.setFontHeightInPoints((short) 12); //Set Header Style CellStyle headerStyle = wb.createCellStyle(); headerStyle.setFillBackgroundColor(IndexedColors.BLACK.getIndex()); headerStyle.setAlignment(headerStyle.ALIGN_CENTER); headerStyle.setFont(headerFont); headerStyle.setBorderBottom(HSSFCellStyle.BORDER_MEDIUM); int rowCount= 0; Row header; header = sheet.createRow(0);//its for header Cell cell ;//= header.createCell(0); for(int j = 0;j < 4; j++) { cell = header.createCell(j); if(j == 0) { cell.setCellValue("ItemWise List"); } cell.setCellStyle(headerStyle); } sheet.addMergedRegion(new CellRangeAddress(rowCount, rowCount, 0, lstReportFormHeader.size()-1)); header = sheet.createRow(0); cell = header.createCell(0); cell.setCellValue("Sr. No"); cell = header.createCell(1); cell.setCellValue("Item Name"); cell = header.createCell(2); cell.setCellValue("Qty"); cell = header.createCell(3); cell.setCellValue("Rate");

Ahora quiero combinar ItemWise List y hacer que se alinee con el centro.


Bueno, lo que funcionó para mí es establecer el estilo de celda de todas las celdas combinadas en CENTRE ALIGN. No importa si pones el método XSSFSheet.addMergedRegion () antes o después de establecer los valores de estilo de celda en el centro.

private void insertXlsHeader(XSSFSheet sheet){ .... //first cell for row1 cell = row1.createCell(colstart); cell.setCellType(org.apache.poi.ss.usermodel.Cell.CELL_TYPE_STRING); cell.setCellValue("COURSES"); setHeaderCellStyle(sheet,cell); //first cell for row2 cell = row2.createCell(colstart); setHeaderCellStyle(sheet,cell); //first cell for row3 cell = row3.createCell(colstart); setHeaderCellStyle(sheet,cell); //merged the first cells of rows 1 to 3 sheet.addMergedRegion(new CellRangeAddress(ROW1, ROW3, colstart, colstart)); ... } private void setHeaderCellStyle(XSSFSheet sheet,org.apache.poi.ss.usermodel.Cell cell) { CellStyle s = null; s = sheet.getWorkbook().createCellStyle(); cell.setCellStyle(s); Font f = sheet.getWorkbook().createFont(); f.setBoldweight(Font.BOLDWEIGHT_BOLD); s.setBorderBottom(CellStyle.BORDER_THIN); s.setBorderLeft(CellStyle.BORDER_THIN); s.setBorderRight(CellStyle.BORDER_THIN); s.setBorderTop(CellStyle.BORDER_THIN); s.setVerticalAlignment(CellStyle.VERTICAL_CENTER); s.setAlignment(CellStyle.ALIGN_CENTER); s.setFont(f); }


Combinar como :::

Workbook wb = new HSSFWorkbook(); Sheet sheet = wb.createSheet("new sheet"); Row row = sheet.createRow((short) 1); Cell cell = row.createCell((short) 1); cell.setCellValue("This is a test of merging"); sheet.addMergedRegion(new CellRangeAddress( 1, //first row (0-based) 1, //last row (0-based) 1, //first column (0-based) 2 //last column (0-based) )); // Write the output to a file FileOutputStream fileOut = new FileOutputStream("workbook.xls"); wb.write(fileOut); fileOut.close();

Para alinear también verifique el enlace oficial de Apache poi :::

http://poi.apache.org/spreadsheet/quick-guide.html#Alignment


Como se respondió anteriormente, la fusión de células se puede lograr usando

sheet.addMergedRegion(new CellRangeAddress(frstRow, lastRow, firstColumnIndex, lastColumnIndex));

Pero para alinear las celdas verticalmente, recientemente tuve un problema similar y traté de responder, pero usando

CellUtil.setAlignment(dataCell, workbook, CellStyle.VERTICAL_CENTER);

alineado Fecha celdas formateadas a horizontal izquierda alineada. Así que utilicé el siguiente método para configurar solo la alineación vertical del contenido de la celda.

CellUtil.setCellStyleProperty(dataCell, workbook,CellUtil.VERTICAL_ALIGNMENT,CellStyle.VERTICAL_CENTER);

¡¡Espero que esto ayude!!

Feliz codificacion


Después del estudio, descubrí que después de fusionar 7 celdas, la identificación de celda combinada será 0, por lo que apliqué el estilo siguiente a la identificación de celda 0 usando el siguiente estilo.

headerStyle.setAlignment(headerStyle.ALIGN_CENTER);


Esto funcionó para mí y creo que es más limpio:

/** * Merge and center the cells specified by range * @param startCell the first cell in the cells to be merged * @param range the range of the cells to be merged */ private static void mergeAndCenter(Cell startCell, CellRangeAddress range) { startCell.getSheet().addMergedRegion(range); CellStyle style = startCell.getSheet().getWorkbook().createCellStyle(); style.setAlignment(CellStyle.ALIGN_CENTER); style.setVerticalAlignment(CellStyle.VERTICAL_CENTER); startCell.setCellStyle(style); }


Mi solución fue fusionar las celdas por sus posiciones, luego creó una celda (referencia al primer bloque de las celdas combinadas) para asignar un valor y luego establecer la alineación a través del CellUtil

// Merges the cells CellRangeAddress cellRangeAddress = new CellRangeAddress(start, start, j, j + 1); sheet.addMergedRegion(cellRangeAddress); // Creates the cell Cell cell = CellUtil.createCell(row, j, entry.getKey()); // Sets the allignment to the created cell CellUtil.setAlignment(cell, workbook, CellStyle.ALIGN_CENTER);


Según mi entendimiento, tiene celdas de inicio y fin para la fusión y desea combinar los rangos de las celdas y alinear el contenido de la celda. Si tengo razón, puedes usar el siguiente método:

/** * @param startCell: first cell of merging area * @param endCell: last cell of merging area */ public static void mergeAndAlignCenter(HSSFCell startCell, HSSFCell endCell){ //finding reference of start and end cell; will result like $A$1 CellReference startCellRef= new CellReference(startCell.getRowIndex(),startCell.getColumnIndex()); CellReference endCellRef = new CellReference(endCell.getRowIndex(),endCell.getColumnIndex()); // forming string of references; will result like $A$1:$B$5 String cellRefernce = startCellRef.formatAsString()+":"+endCellRef.formatAsString(); //removing $ to make cellRefernce like A1:B5 cellRefernce = cellRefernce.replace("$",""); //passing cellRefernce to make a region CellRangeAddress region = CellRangeAddress.valueOf(cellRefernce); //use region to merge; though other method like sheet.addMergedRegion(new CellRangeAddress(1,1,4,1)); // is also available, but facing some problem right now. startCell.getRow().getSheet().addMergedRegion( region ); //setting alignment to center CellUtil.setAlignment(startCell, wb, CellStyle.ALIGN_CENTER); }


Use style.setVerticalAlignment () para establecer las alineaciones verticales en lugar de style.setAlignment ().