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.           
  3.         Workbook wb=new HSSFWorkbook();  
  4.           
  5.         Sheet sheet=wb.createSheet();  
  6.         /* 
  7.          * 設定合併單元格區域範圍 
  8.          *  firstRow  0-based 
  9.          *  lastRow   0-based 
  10.          *  firstCol  0-based 
  11.          *  lastCol   0-based 
  12.          */  
  13.         CellRangeAddress cra=new CellRangeAddress(0339);        
  14.           
  15.         //在sheet裏增加合併單元格  
  16.         sheet.addMergedRegion(cra);  
  17.           
  18.         Row row = sheet.createRow(0);  
  19.           
  20.         Cell cell_1 = row.createCell(3);  
  21.           
  22.         cell_1.setCellValue("When you're right , no one remembers, when you're wrong ,no one forgets .");  
  23.           
  24.         //cell 位置3-9被合併成一個單元格,不管你怎樣創建第4個cell還是第5個cell…然後在寫數據。都是無法寫入的。  
  25.         Cell cell_2 = row.createCell(10);  
  26.           
  27.         cell_2.setCellValue("what's up ! ");  
  28.           
  29.         wb.write(fos);  
  30.           
  31.         fos.close();
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章