poi操作Word合并单元格

来源:互联网 发布:数据库系统特点 编辑:程序博客网 时间:2024/05/10 09:05

对于合并单元格的介绍不怎么多,下面是之前做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.     }  
转载自: POI操作word合并单元格

另:(设值)

    private static void fillTable(XWPFTable table) {        for (int rowIndex = 0; rowIndex < table.getNumberOfRows(); rowIndex++) {            XWPFTableRow row = table.getRow(rowIndex);            for (int colIndex = 0; colIndex < row.getTableCells().size(); colIndex++) {                XWPFTableCell cell = row.getCell(colIndex);                cell.addParagraph().createRun().setText(" cell " + rowIndex + colIndex + " ");            }        }    }

相关参考:[简单]poi word2007表格单元格合并

原创粉丝点击