合並單元格所使用的方法:
sheet.addMergedRegion( CellRangeAddress cellRangeAddress );
CellRangeAddress 對象的構造方法需要傳入合並單元格的首行、最后一行、首列、最后一列。
CellRangeAddress cra=new CellRangeAddress(0, 3, 3, 9);
怎樣把數據寫入合並后的單元格中
- 首先要查看你 CellRangeAddress 構造方法的firstcol index
- 創建firstcol cell對象
- cell 的set 方法寫數據
在合並單元格的后一個位置寫數據
- 查看 CellRangeAddress 構造方法的lastcol index
- 創建lastcol+1 cell
- cell 的set方法寫數據
以下是demo:
- FileOutputStream fos=new FileOutputStream("D:\\13.xls");
- Workbook wb=new HSSFWorkbook();
- Sheet sheet=wb.createSheet();
- /*
- * 設定合並單元格區域范圍
- * firstRow 0-based
- * lastRow 0-based
- * firstCol 0-based
- * lastCol 0-based
- */
- CellRangeAddress cra=new CellRangeAddress(0, 3, 3, 9);
- //在sheet里增加合並單元格
- sheet.addMergedRegion(cra);
- Row row = sheet.createRow(0);
- Cell cell_1 = row.createCell(3);
- cell_1.setCellValue("When you're right , no one remembers, when you're wrong ,no one forgets .");
- //cell 位置3-9被合並成一個單元格,不管你怎樣創建第4個cell還是第5個cell…然后在寫數據。都是無法寫入的。
- Cell cell_2 = row.createCell(10);
- cell_2.setCellValue("what's up ! ");
- wb.write(fos);
- fos.close();