Apache 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:

 

[java]  view plain  copy
 
 在CODE上查看代碼片派生到我的代碼片
  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(0, 3, 3, 9);        
  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();  


 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM