同一行上合并了多个单元格问题:
应该从后向前合并单元格 因为从前向后合并单元格,合并之后的单元格下标就乱了,我也是刚刚解决这个问题,我是这样做的。
XSSFSheet sheet = newWorkBook.createSheet("报表1"); for(int i=3;i>-1;i--){ sheet.addMergedRegion(new CellRangeAddress(0,0, i*7+0, i*7+6)); }
合并单元格并添加边框
方法1:
private static void setRegionBorder(int border, CellRangeAddress region, Sheet sheet,Workbook wb){ CellStyle cs=wb.createCellStyle(); cs.setBorderBottom((short) border); cs.setBorderTop((short) border); cs.setBorderLeft((short) border); cs.setBorderRight((short) border); setRegionStyle( cs, region, sheet); } private static void setRegionStyle(CellStyle cs, CellRangeAddress region, Sheet sheet){ for(int i=region.getFirstRow();i<=region.getLastRow();i++){ Row row=sheet.getRow(i); if(row==null) row=sheet.createRow(i); for(int j=region.getFirstColumn();j<=region.getLastColumn();j++){ Cell cell=row.getCell(j); if( cell==null){ cell=row.createCell(j); cell.setCellValue(""); } cell.setCellStyle(cs); } } }
注意:如果合并在前,则在后面不能直接用
Row row=sheet.createRow(0);
而应该改为
Row row=sheet.getRow(0);
if(row==null){
row2=sheet.createRow(2);
}
否则直接createRow会覆盖先前合并时定义的边框样式。
方法2:可以用poi自带的工具类来处理合并后的边框
private static void setRegionBorder(int border, CellRangeAddress region, Sheet sheet,Workbook wb){ RegionUtil.setBorderBottom(border,region, sheet, wb); RegionUtil.setBorderLeft(border,region, sheet, wb); RegionUtil.setBorderRight(border,region, sheet, wb); RegionUtil.setBorderTop(border,region, sheet, wb); }