// 模板路径
ClassPathResource classPathResource = new ClassPathResource("/templates/DailyTemplate.docx");
try (InputStream inputStream = classPathResource.getInputStream()) {
Document document = new Document(inputStream);
// 表格模板路径
ClassPathResource tablePathResource = new ClassPathResource("/templates/TableDailyTemplate.docx");
try (InputStream tableInputStream = tablePathResource.getInputStream()) {
Document table = new Document(tableInputStream);
// 获取源文档中的表格
Table tableToCopy = (Table) table.getChild(NodeType.TABLE, 0, true);
// 因为表格从第四行开始是需要动态增长的,所以取第四行作为模板
Row baseRow = tableToCopy.getRows().get(4);
// 插入数据
for (int i = 0; i < dtoList.size(); i++) {
DataDTO dataDTO = dtoList.get(i);
Row newRow;
if (i == 0) {
// 第一行数据直接录入模板行
newRow = baseRow;
} else {
// 深度克隆模板行,含样式
newRow = (Row) baseRow.deepClone(true);
}
// 设置第一列值,后续所有列都可参照该方式设置
Cell newCell = newRow.getCells().get(0);
newCell.removeAllChildren();
newCell.appendChild(new Paragraph(table));
newCell.getFirstParagraph().appendChild(new Run(table, dataDTO.getCode()));
// 内容居中
newCell.getFirstParagraph().getParagraphFormat().setAlignment(ParagraphAlignment.CENTER);
if (i > 0) {
// 非模板行插入行
tableToCopy.getRows().insert(4 + i, newRow);
}
}
// 克隆表格到目标文档
Node importedNode = document.importNode(tableToCopy, true);
document.getLastSection().getBody().appendChild(importedNode);
// 以下内容为需要动态往word文档中插入多个表格模板时分隔表格的方式
// 创建分页符
Paragraph blankParagraph = new Paragraph(document);
Run run = new Run(document);
run.setText(ControlChar.PAGE_BREAK); // 插入分页控制字符
blankParagraph.appendChild(run);
// 插入分页符
document.getLastSection().getBody().appendChild(blankParagraph);
// // 创建空白段落
// Paragraph blankParagraph = new Paragraph(document);
// blankParagraph.appendChild(new Run(document, "\n"));
// blankParagraph.getParagraphFormat().setSpaceBefore(10); // 设置段前间距
// blankParagraph.getParagraphFormat().setSpaceAfter(10); // 设置段后间距
// // 插入空白行
// document.getLastSection().getBody().appendChild(blankParagraph);
}
// 检测最后的内容是否是分页符,如果是则移除,避免空白页
Body body = document.getLastSection().getBody();
Node lastNode = body.getLastChild();
if (lastNode instanceof Paragraph) {
Paragraph lastPara = (Paragraph) lastNode;
Node lastRunNode = lastPara.getLastChild();
if (lastRunNode instanceof Run) {
Run lastRun = (Run) lastRunNode;
if (lastRun.getText().equals(ControlChar.PAGE_BREAK)) {
// 情况 1:段落仅包含分页符 Run,直接删除整个段落
if (lastPara.getChildNodes().getCount() == 1) {
body.removeChild(lastNode);
}
// 情况 2:段落包含其他内容,仅删除分页符 Run
else {
lastPara.removeChild(lastRun);
}
}
}
}
// 保存文件为word文档
document.save("D:\demo.docx", SaveFormat.DOCX);
// 保存文件为pdf
document.save("D:\demo.pdf", SaveFormat.PDF);
}
最后修改:2025 年 03 月 28 日
© 允许规范转载