只研究了
表格内多行循环
,表格循环
,段落循环
因为篇幅缘由,只展现重要代码。看懂此文代码可能需结合下面连接里模版说明.docx
若有不对,欢迎指正。 代码传送门🔗:gitee.com/street1corn…java
参考连接:blog.csdn.net/u012775558/…git
/* 循环生成模板行 */
// 获取到模版行的行数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));// 处理标签替换
}
}
}
复制代码
首先pom的poi的版本要是
3.17
以上,楼主曾用3.13
,试了半天图片显示有问题,最终才想到升级版本解决问题。(这是一大坑,必定要注意)apache
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
复制代码
在最小单元
run
里边得到其中的图片并add进新的run
中去(一个XWPFRun表明具备相同属性的一个区域)spa
思路参考连接:stackoverflow.com/questions/1….net
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();
}
}
}
复制代码
原连接中 code
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);
}
}
复制代码