之前这篇文章丢失,现找回重新发布
只研究了 表格内多行循环,表格循环,段落循环
由于篇幅原因,只展示重要代码。看懂此文代码可能需结合下面链接里 模版说明.docx
如有不对,欢迎指正。
参考链接:blog.csdn.net/u012775558/…
表格内多行循环
/* 循环生成模板行 */
// 获取到模版行的行数tempRowsCountInt
String tempRowsCount = TempTableRows.get(tagRowsIndex).getTableCells().get(1).getText();
System.out.println("读取到模版行数为:" + tempRowsCount);
int tempRowsCountInt = 1;
if(tempRowsCount == null || "".equals(tempRowsCount)) {
tempRowsCountInt = 1;
}else {
tempRowsCountInt = Integer.parseInt(tempRowsCount);
}
// XWPFTableRow tempRow1 = TempTableRows.get(tagRowsIndex + 1);// 获取到模板行
for (int i = 0; i < list.size(); i++) {
//模版行为1行,多行
if(tempRowsCountInt == 1) {
XWPFTableRow tempRow = TempTableRows.get(tagRowsIndex + 1);// 获取到模板行
XWPFTableRow newCreateRow = newCreateTable.createRow();
CopyTableRow(newCreateRow, tempRow);// 复制模板行
replaceTableRow(newCreateRow, list.get(i));// 处理标签替换
}else {
//循环模版行
for(int j = 0;j < tempRowsCountInt; j++) {
XWPFTableRow tempRow = TempTableRows.get(tagRowsIndex + j + 1);// 获取到模板行
XWPFTableRow newCreateRow = newCreateTable.createRow();
CopyTableRow(newCreateRow, tempRow);// 复制模板行
replaceTableRow(newCreateRow, list.get(i));// 处理标签替换
}
}
}
word替换-图片丢失解决
在最小单元run里边获得其中的图片并add进新的run中去
思路参考链接:stackoverflow.com/questions/1…
if (templateRun.getEmbeddedPictures().size() > 0) {
for (XWPFPicture pic : templateRun.getEmbeddedPictures()) {
byte[] img = pic.getPictureData().getData();
long cx = pic.getCTPicture().getSpPr().getXfrm().getExt().getCx();
long cy = pic.getCTPicture().getSpPr().getXfrm().getExt().getCy();
try {
newRun.addPicture(new ByteArrayInputStream(img), XWPFDocument.PICTURE_TYPE_PNG, "", (int)cx, (int)cy);
} catch (InvalidFormatException | IOException e1) {
e1.printStackTrace();
}
}
}
段落循环
原链接中
新增
else if (flag == 1) {// 段落整体循环
for (Map<String, Object> map : list) {
XWPFParagraph createParagraph = document.createParagraph();
// 设置段落样式
createParagraph.getCTP().setPPr(templateParagraph.getCTP().getPPr());
// 移除原始内容
for (int pos = 0; pos < createParagraph.getRuns().size(); pos++) {
createParagraph.removeRun(pos);
}
// 添加Run标签并删除首行####
for(int i = 0; i<templateParagraph.getRuns().size(); i++) {
XWPFRun s = templateParagraph.getRuns().get(i);
//第一个run删除多余的字符
if(i == 0) {
XWPFRun targetrun = createParagraph.createRun();
targetrun.getCTR().setRPr(s.getCTR().getRPr());
// 设置文本
targetrun.setText(s.text().substring(2));
continue;
}
XWPFRun targetrun = createParagraph.createRun();
CopyRun(targetrun, s);
}
replaceParagraph(createParagraph, map);
}
}