只研究了
表格內多行循環
,表格循環
,段落循環
因爲篇幅緣由,只展現重要代碼。看懂此文代碼可能需結合下面連接裏模版說明.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);
}
}
複製代碼