POI操作word合并单元格

对于合并单元格的介绍不怎么多,下面是之前做word导出的时候研究的,在stackoverflow查到了点资料。

记录下两个关键方法:

[java]  view plain  copy
  1. // word跨列合并单元格  
  2.     public  void mergeCellsHorizontal(XWPFTable table, int row, int fromCell, int toCell) {    
  3.         for (int cellIndex = fromCell; cellIndex <= toCell; cellIndex++) {    
  4.             XWPFTableCell cell = table.getRow(row).getCell(cellIndex);    
  5.             if ( cellIndex == fromCell ) {    
  6.                 // The first merged cell is set with RESTART merge value    
  7.                 cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.RESTART);    
  8.             } else {    
  9.                 // Cells which join (merge) the first one, are set with CONTINUE    
  10.                 cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.CONTINUE);    
  11.             }    
  12.         }    
  13.     }    
  14.     // word跨行并单元格  
  15.     public void mergeCellsVertically(XWPFTable table, int col, int fromRow, int toRow) {    
  16.         for (int rowIndex = fromRow; rowIndex <= toRow; rowIndex++) {    
  17.             XWPFTableCell cell = table.getRow(rowIndex).getCell(col);    
  18.             if ( rowIndex == fromRow ) {    
  19.                 // The first merged cell is set with RESTART merge value    
  20.                 cell.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.RESTART);    
  21.             } else {    
  22.                 // Cells which join (merge) the first one, are set with CONTINUE    
  23.                 cell.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.CONTINUE);    
  24.             }    
  25.         }    
  26.     }   

另外加上单元格字体设置的方法:

[html]  view plain  copy
  1. private void getParagraph(XWPFTableCell cell,String cellText){  
  2.         CTP ctp = CTP.Factory.newInstance();  
  3.         XWPFParagraph p = new XWPFParagraph(ctp, cell);  
  4.         p.setAlignment(ParagraphAlignment.CENTER);  
  5.         XWPFRun run = p.createRun();  
  6.         run.setText(cellText);  
  7.         CTRPr rpr = run.getCTR().isSetRPr() ? run.getCTR().getRPr() : run.getCTR().addNewRPr();  
  8.         CTFonts fonts = rpr.isSetRFonts() ? rpr.getRFonts() : rpr.addNewRFonts();  
  9.         fonts.setAscii("仿宋");  
  10.         fonts.setEastAsia("仿宋");  
  11.         fonts.setHAnsi("仿宋");  
  12.         cell.setParagraph(p);  
  13.     }  
转自:http://blog.csdn.net/rudy1245/article/details/53421366

猜你喜欢

转载自blog.csdn.net/free_wind22/article/details/79202522