Java POI word常用方法 在Cell插入子表格

  1. 替换文本,段落不能直接插入(setText)内容,因为setText会把内容追加在原来内容的后面
/**
 * 替换文本
 *
 * @param key
 * @param value
 * @param paragraph
 */
public void replaceAllText(String key, String value, XWPFParagraph paragraph) {
    String text = paragraph.getText();
    if (StrUtil.isNotEmpty(text) && text.indexOf(key) != -1) {
        List<XWPFRun> runs = paragraph.getRuns();
        for (int i = (runs.size() - 1); i > 0; i--) {
            paragraph.removeRun(i);
        }
        runs.get(0).setText(text.replace(key, value), 0);
    }
}
  1. cell插入表格,在单元格里插入表格
XWPFTable cellTable = cell.insertNewTbl(qyCursorParagraph.getCTP().newCursor());//游标代表插入的位置
cellTable.getCTTbl().setTblPr(tableInitOne.getCTTbl().getTblPr());
  1. 复制表格行
/**
 * 复制表格行
 *  * @param table
 * @param sourceRow
 * @param rowIndex
 */
public void copy(XWPFTable table, XWPFTableRow sourceRow, int rowIndex) {
    //在表格指定位置新增一行
    XWPFTableRow targetRow = table.insertNewTableRow(rowIndex);
    //复制行属性
    targetRow.getCtRow().setTrPr(sourceRow.getCtRow().getTrPr());
    List<XWPFTableCell> cellList = sourceRow.getTableCells();
    if (null == cellList) {
        return;
    }
    //复制列及其属性和内容
    XWPFTableCell targetCell = null;
    for (XWPFTableCell sourceCell : cellList) {
        targetCell = targetRow.addNewTableCell();
        //列属性
        targetCell.getCTTc().setTcPr(sourceCell.getCTTc().getTcPr());
        //段落属性
        if (sourceCell.getParagraphs() != null && sourceCell.getParagraphs().size() > 0) {
            targetCell.getParagraphs().get(0).getCTP().setPPr(sourceCell.getParagraphs().get(0).getCTP().getPPr());
            if (sourceCell.getParagraphs().get(0).getRuns() != null && sourceCell.getParagraphs().get(0).getRuns().size() > 0) {
                XWPFRun cellR = targetCell.getParagraphs().get(0).createRun();
                cellR.setText(sourceCell.getText());
                cellR.setBold(sourceCell.getParagraphs().get(0).getRuns().get(0).isBold());
                cellR.setFontSize(8);
                cellR.setFontFamily("仿宋");
            } else {
                targetCell.setText(sourceCell.getText());
            }
        } else {
            targetCell.setText(sourceCell.getText());
        }
    }
}

Java操作word组件 :

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值