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:
- // word merge cells across columns
- publicvoid 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 across rows and cells
- publicvoid 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);
- }
- }
- }
In addition, add the method of cell font setting:
- 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("Fake Song Dynasty");
- fonts.setEastAsia("Fake Song Dynasty");
- fonts.setHAnsi("Fake Song Dynasty");
- cell.setParagraph(p);
- }