1.word模板替换功能公共类,调整动态行数代码逻辑

This commit is contained in:
wr
2024-06-25 10:58:52 +08:00
parent 0677320a06
commit 234f0be465
2 changed files with 11 additions and 13 deletions

View File

@@ -30,7 +30,7 @@ public class WordUtil2 {
this.replaceInTable(doc, params); // 替换表格里面的变量
this.replaceInPara(doc, params); // 替换文本里面的变量
} catch (IOException e) {
logger.error("获取报告模板异常,原因为:" + e.toString());
logger.error("获取报告模板异常,原因为:" + e);
} finally {
if (null != inStream) {
inStream.close();
@@ -43,7 +43,7 @@ public class WordUtil2 {
doc.write(outputStream);
outputStream.close();
} catch (Exception e) {
logger.error("输出稳态报告异常,原因为:" + e.toString());
logger.error("输出稳态报告异常,原因为:" + e);
} finally {
if (doc != null) {
doc.close();
@@ -210,19 +210,15 @@ public class WordUtil2 {
* @param tableList 插入数据集合
*/
private static void insertTable(XWPFTable table, List<String[]> tableList) {
//删除占位符行数
table.removeRow(1);
// 创建行,根据需要插入的数据添加新行,不处理表头
for (int i = 0; i < tableList.size(); i++) {
XWPFTableRow row = table.createRow();
}
// 遍历表格插入数据
List<XWPFTableRow> rows = table.getRows();
int length = table.getRows().size();
for (int i = 1; i < length - 1; i++) {
XWPFTableRow newRow = table.getRow(i);
List<XWPFTableCell> cells = newRow.getTableCells();
List<XWPFTableCell> cells = row.getTableCells();
for (int j = 0; j < cells.size(); j++) {
XWPFTableCell cell = cells.get(j);
String s = tableList.get(i - 1)[j];
String s = tableList.get(i)[j];
cell.setText(s);
}
}
@@ -232,14 +228,16 @@ public class WordUtil2 {
* 替换表格里面的变量
*
* @param doc 要替换的文档
* @param tableList 存放数据顺序要与表格一致
* @param params 参数
*/
private void replaceInTable(CustomXWPFDocument doc, Map<String, Object> params, List<String[]> tableList) {
private void replaceInTable(CustomXWPFDocument doc, Map<String, Object> params, List<List<String[]>> tableList) {
Iterator<XWPFTable> iterator = doc.getTablesIterator();
XWPFTable table;
List<XWPFTableRow> rows;
List<XWPFTableCell> cells;
List<XWPFParagraph> paras;
Integer num=0;
while (iterator.hasNext()) {
table = iterator.next();
if (table.getRows().size() > 1) {
@@ -256,7 +254,8 @@ public class WordUtil2 {
}
}
} else {
insertTable(table, tableList); // 插入数据
insertTable(table, tableList.get(num)); // 插入数据
num++;
}
}
}