1. 程式人生 > >java POI 實現合併單元格

java POI 實現合併單元格

合併單元格所使用的方法: sheet.addMergedRegion( CellRangeAddress  cellRangeAddress  ); CellRangeAddress  物件的構造方法需要傳入合併單元格的首行、最後一行、首列、最後一列。 CellRangeAddress cra=new CellRangeAddress(0, 3, 3, 9); 怎樣把資料寫入合併後的單元格中
  1. 首先要檢視你 CellRangeAddress 構造方法的firstcol index
  2. 建立firstcol cell物件
  3. cell 的set 方法寫資料
在合併單元格的後一個位置寫資料
  1. 檢視  CellRangeAddress 構造方法的lastcol index     
  2. 建立lastcol+1  cell
  3. cell 的set方法寫資料

以下是demo:

  1. FileOutputStream fos=new FileOutputStream("D:\\13.xls");  
  2.         Workbook wb=new HSSFWorkbook();  
  3.         Sheet sheet=wb.createSheet();  
  4.         /* 
  5.          * 設定合併單元格區域範圍 
  6.          *  firstRow  0-based 
  7.          *  lastRow   0-based 
  8.          *  firstCol  0-based
     
  9.          *  lastCol   0-based 
  10.          */
  11.         CellRangeAddress cra=new CellRangeAddress(0339);        
  12.         //在sheet裡增加合併單元格
  13.         sheet.addMergedRegion(cra);  
  14.         Row row = sheet.createRow(0);  
  15.         Cell cell_1 = row.createCell(3);  
  16.         cell_1.setCellValue("When you're right , no one remembers, when you're wrong ,no one forgets ."
    );  
  17.         //cell 位置3-9被合併成一個單元格,不管你怎樣建立第4個cell還是第5個cell…然後在寫資料。都是無法寫入的。
  18.         Cell cell_2 = row.createCell(10);  
  19.         cell_2.setCellValue("what's up ! ");  
  20.         wb.write(fos);  
  21.         fos.close();