Could anyone explain me how to create the borders for the merged cells using Apache POI?
The Code I'm using is only affecting one cell.
sheet.addMergedRegion(new CellRangeAddress(1, 1, 2, 3));
Cell monthCell = subheaderRow.createCell(2);
monthCell.setCellValue(2);
monthCell.setCellStyle(styles.get("month"));
style = wb.createCellStyle();
style.setBorderBottom(CellStyle.BORDER_THIN);
style.setBorderTop(CellStyle.BORDER_THIN);
style.setBorderLeft(CellStyle.BORDER_THIN);
style.setBorderRight(CellStyle.BORDER_THIN);
style.setAlignment(CellStyle.ALIGN_CENTER);
style.setAlignment(CellStyle.ALIGN_CENTER);
style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
// style.setFillForegroundColor(IndexedColors.DARK_BLUE.getIndex());
// style.setFillPattern(CellStyle.SOLID_FOREGROUND);
// style.setFont(monthFont);
styles.put("month", style);
You need to assign same style (in your case style that includes the border) to each cell you are merging. My suggestion create a function that checks and corrects, sets style to all cells in the merging region. Here is example of my own: private static final XSSFColor COLOR_ORANGE = new XSSFColor(new java.
In some situation you can't work with workbook that consists of merged cells. To use Filter, Sort or other functions, you need to unmerge cells and put to all of them the data from merged cells.
This can be done as below:
public void doMerge(int rowIndex, int columnIndex, int rowSpan, int columnSpan) {
Cell cell = sheet.getRow(rowIndex).getCell(columnIndex);
CellRangeAddress range = new CellRangeAddress(rowIndex, rowIndex + rowSpan - 1, columnIndex, columnIndex
+ columnSpan - 1);
sheet.addMergedRegion(range);
RegionUtil.setBorderBottom(cell.getCellStyle().getBorderBottom(), range, sheet, sheet.getWorkbook());
RegionUtil.setBorderTop(cell.getCellStyle().getBorderTop(), range, sheet, sheet.getWorkbook());
RegionUtil.setBorderLeft(cell.getCellStyle().getBorderLeft(), range, sheet, sheet.getWorkbook());
RegionUtil.setBorderRight(cell.getCellStyle().getBorderRight(), range, sheet, sheet.getWorkbook());
RegionUtil.setBottomBorderColor(cell.getCellStyle().getBottomBorderColor(), range, sheet, sheet.getWorkbook());
RegionUtil.setTopBorderColor(cell.getCellStyle().getTopBorderColor(), range, sheet, sheet.getWorkbook());
RegionUtil.setLeftBorderColor(cell.getCellStyle().getLeftBorderColor(), range, sheet, sheet.getWorkbook());
RegionUtil.setRightBorderColor(cell.getCellStyle().getRightBorderColor(), range, sheet, sheet.getWorkbook());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With