POI operation word merge cells

There is not much introduction to merging cells. The following is what I studied when I did word export before, and I found some information on stackoverflow.

Two key methods are noted:

[java]  view plain  copy
  1. // word merge cells across columns  
  2.     publicvoid 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 across rows and cells  
  15.     publicvoid 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.     }   

In addition, add the method of cell font setting:

[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("Fake Song Dynasty");  
  10.         fonts.setEastAsia("Fake Song Dynasty");  
  11.         fonts.setHAnsi("Fake Song Dynasty");  
  12.         cell.setParagraph(p);  
  13.     }  
Reprinted from: http://blog.csdn.net/rudy1245/article/details/53421366

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325759164&siteId=291194637