POI合并单元格边框显示问题,笨方法解决。如有更好的方法,欢迎留言,求指教告知

网上找了好多关于POI合并单元格的文章,无奈智商捉鸡,玩不出来,最后弄了个最麻烦的

//导出excel,含有合并单元格

@Test

public void exoprtExc_MergedRegion() {

String realpath = PoiTemplate.class.getResource(“/”).getPath() + “土地报批台账.xls”;

String destPath = “C:\\Users\\Administrator\\Desktop\\test1.xls”;

try {

POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(realpath));

//读取excel模板

HSSFWorkbook wb = new HSSFWorkbook(fs);

//读取模板内所有的sheet内容

HSSFSheet sheet = wb.getSheetAt(0);

// 设置表格默认列宽度为15个字节  

sheet.setDefaultColumnWidth(15);

//生成一个样式

HSSFCellStyle style = wb.createCellStyle();

//设置边框

style.setBorderBottom(HSSFCellStyle.BORDER_THIN);

style.setBorderLeft(HSSFCellStyle.BORDER_THIN);

style.setBorderRight(HSSFCellStyle.BORDER_THIN);

style.setBorderTop(HSSFCellStyle.BORDER_THIN);

//设置居中

style.setAlignment(HSSFCellStyle.ALIGN_CENTER);

style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

//生成一个字体

HSSFFont font = wb.createFont();

font.setFontHeightInPoints((short)10);

font.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);

style.setFont(font);

//合并单元格区域的范围

int startRow = 5;

int endRow = 5;

int startCol = 0;

int endCol = 0;

int childNum = 3;
//表示行级合并单元格的大小

int length = startRow + childNum * 5;
//最大的行数

//首先写出全部的单元格,设为空值,为了合并单元格显示边框

for(int i = startRow;i < length;i++){

HSSFRow row = sheet.createRow(i);

for (int j = 0; j < 29; j++) {

HSSFCell cell = row.createCell(j);  

cell.setCellStyle(style);  

cell.setCellValue(“”); 

}

}

startRow = 5;

endRow = 5;

for (int i = startRow; i < length;) {
//行

endRow = startRow + childNum – 1;

HSSFRow row = sheet.getRow(i);

//合并主集行

for (int j = 0; j < 7; j++) {
//列

//给第一个单元格赋值

HSSFCell cell = row.getCell(j); 

cell.setCellValue(i + “,” + j);  

//合并单元格

startCol = j;

endCol = j;

CellRangeAddress cra = new CellRangeAddress(startRow, endRow, startCol, endCol);

sheet.addMergedRegion(cra);

//给合并单元格的其他单元格赋空值,不然出来的表格有的单元格没有边框

//setCRAStyle(sheet,startRow, endRow, startCol, endCol,style);

}

//子集行的展示

if(childNum > 0){

//首行默认加载一行子集数据

for (int x = 7; x < 11; x++) {
//列

HSSFCell cell = row.getCell(x);  

cell.setCellStyle(style);  

cell.setCellValue(i + “,” + x);  

}

for (int a = startRow + 1; a <= endRow ; a++) {

HSSFRow tempRow = sheet.getRow(a);

for (int b = 7; b < 11; b++) {
//列

HSSFCell cell = tempRow.getCell(b);  

cell.setCellStyle(style);  

cell.setCellValue(a + “,” + b);  

}

}

}

//合并主集行

for (int y = 11; y < 29; y++) {
//列

HSSFCell cell = row.getCell(y);  

cell.setCellValue(i + “,” + y); 

startCol = y;

endCol = y;

CellRangeAddress cra = new CellRangeAddress(startRow, endRow, startCol, endCol);

sheet.addMergedRegion(cra);

}

startRow = endRow + 1;

i = startRow;

}

wb.write(new FileOutputStream(destPath));

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

}

    原文作者:骑士周游问题
    原文地址: https://blog.csdn.net/u014246075/article/details/54583383
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞