java POI 實現合併單元格
阿新 • • 發佈:2019-02-04
合併單元格所使用的方法:
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();