- 替换文本,段落不能直接插入(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);
}
}
- cell插入表格,在单元格里插入表格
XWPFTable cellTable = cell.insertNewTbl(qyCursorParagraph.getCTP().newCursor());//游标代表插入的位置
cellTable.getCTTbl().setTblPr(tableInitOne.getCTTbl().getTblPr());
- 复制表格行
/**
* 复制表格行
* * @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组件 :
- XDocReport
- POI Apache POI Word(docx) 入门示例教程
- poi-tl 【中文文档】