对于合并单元格的介绍不怎么多,下面是之前做word导出的时候研究的,在stackoverflow查到了点资料。
记录下两个关键方法:
-
- 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 ) {
-
- cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.RESTART);
- } else {
-
- cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.CONTINUE);
- }
- }
- }
-
- 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 ) {
-
- cell.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.RESTART);
- } else {
-
- 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);
- }
转载自:
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表格单元格合并