对于合并单元格的介绍不怎么多,下面是之前做word导出的时候研究的,在stackoverflow查到了点资料。
记录下两个关键方法:
- // word跨列合并单元格
- public void mergeCellsHorizontal(XWPFTable table, int row, int fromCell, int toCell) {
- for (int cellIndex = fromCell; cellIndex <= toCell; cellIndex++) {
- XWPFTableCell cell = table.getRow(row).getCell(cellIndex);
- if ( cellIndex == fromCell ) {
- // The first merged cell is set with RESTART merge value
- cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.RESTART);
- } else {
- // Cells which join (merge) the first one, are set with CONTINUE
- cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.CONTINUE);
- }
- }
- }
- // word跨行并单元格
- public void mergeCellsVertically(XWPFTable table, int col, int fromRow, int toRow) {
- for (int rowIndex = fromRow; rowIndex <= toRow; rowIndex++) {
- XWPFTableCell cell = table.getRow(rowIndex).getCell(col);
- if ( rowIndex == fromRow ) {
- // The first merged cell is set with RESTART merge value
- cell.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.RESTART);
- } else {
- // Cells which join (merge) the first one, are set with CONTINUE
- cell.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.CONTINUE);
- }
- }
- }
另外加上单元格字体设置的方法:
- private void getParagraph(XWPFTableCell cell,String cellText){
- CTP ctp = CTP.Factory.newInstance();
- XWPFParagraph p = new XWPFParagraph(ctp, cell);
- p.setAlignment(ParagraphAlignment.CENTER);
- XWPFRun run = p.createRun();
- run.setText(cellText);
- CTRPr rpr = run.getCTR().isSetRPr() ? run.getCTR().getRPr() : run.getCTR().addNewRPr();
- CTFonts fonts = rpr.isSetRFonts() ? rpr.getRFonts() : rpr.addNewRFonts();
- fonts.setAscii("仿宋");
- fonts.setEastAsia("仿宋");
- fonts.setHAnsi("仿宋");
- cell.setParagraph(p);
- }