poi导出excel 纵向合并单元格后,边框消失的问题。
如上图,原本是合并了A/B/C/D/E列的第2、3行。但边框却有了。
网上搜索了几篇文章,最后是以下网址中得到答案:
https://zhouchaofei2010.iteye.com/blog/1070857
具体解决办法记录如下:
//合并A~J列第1、2行:
CellRangeAddress region1 = new CellRangeAddress(1, 2, 0, 0);
sheet.addMergedRegion(region1);
setBorderStyle(HSSFCellStyle.BORDER_THIN, region1, sheet, wb); //给合并过的单元格加边框。。。。。。后面代码类似,省略。
//很关键:
//在sheet里创建第二行
//HSSFRow row2 =sheet.createRow(1); //不能这样直接新增,否则直接createRow会覆盖先前合并时定义的边框样式。
HSSFRow row2 = sheet.getRow(1);
if(row2==null)
{
row2 = sheet.createRow(1);
}
//在sheet里创建第3行
//HSSFRow row3 = sheet.createRow(2);
HSSFRow row3 = sheet.getRow(2);
if(row3==null)
{
row3 = sheet.createRow(2);
}
//用poi自带的工具类来处理合并后的边框
public void setBorderStyle(int border,CellRangeAddress region,HSSFSheet sheet,HSSFWorkbook 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);
}
/*
//也可用以下方法
public void setBorderStyle(int border,CellRangeAddress region,HSSFSheet sheet,HSSFWorkbook wb){
HSSFCellStyle 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(HSSFCellStyle cs, CellRangeAddress region, HSSFSheet sheet){
for(int i=region.getFirstRow();i<=region.getLastRow();i++){
HSSFRow row=sheet.getRow(i);
if(row==null) row=sheet.createRow(i);
for(int j=region.getFirstColumn();j<=region.getLastColumn();j++){
HSSFCell cell=row.getCell(j);
if( cell==null){
cell=row.createCell(j);
cell.setCellValue("");
}
cell.setCellStyle(cs);
}
}
}
*/