1. 程式人生 > >POI合併單元格邊框顯示問題,笨方法解決。如有更好的方法,歡迎留言,求指教告知

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();
}
}