package com.product.print.util;
|
|
import cn.hutool.core.util.ArrayUtil;
|
import com.deepoove.poi.config.Configure;
|
import com.deepoove.poi.render.RenderContext;
|
import com.deepoove.poi.template.run.RunTemplate;
|
import com.product.core.exception.BaseException;
|
import com.product.print.config.CmnCode;
|
import org.apache.poi.xwpf.usermodel.*;
|
|
import java.util.List;
|
import java.util.regex.Matcher;
|
import java.util.regex.Pattern;
|
|
/**
|
* @Author cheng
|
* @Date 2023/8/7 10:04
|
* @Desc 表格数据空时
|
*/
|
public class TableEmptyHandler extends Configure.ClearHandler {
|
|
private String[] tagName;
|
|
public TableEmptyHandler() {
|
}
|
|
public void addTag(String tagName) {
|
if (this.tagName == null) {
|
this.tagName = new String[]{};
|
}
|
this.tagName = ArrayUtil.append(this.tagName, tagName);
|
}
|
|
@Override
|
public void handler(RenderContext<?> context) {
|
String tagName = context.getEleTemplate().getTagName();
|
if (this.tagName == null || ArrayUtil.indexOf(this.tagName, tagName) == -1) {
|
super.handler(context);
|
return;
|
}
|
RunTemplate runTemplate = (RunTemplate) context.getEleTemplate();
|
XWPFRun run = runTemplate.getRun();
|
XWPFTableCell cell = (XWPFTableCell) ((XWPFParagraph) run.getParent()).getBody();
|
XWPFTable xwpfTable = cell.getTableRow().getTable();
|
doRemove(xwpfTable, tagName);
|
}
|
|
private void doRemove(XWPFTable xwpfTable, String tagName) {
|
|
List<XWPFTableRow> rows = xwpfTable.getRows();
|
//读取rows中的内容
|
String tableExpression = "{{" + tagName + "}}";
|
//获取表格起始行和结束行
|
int startRowIndex = -1;
|
rows:
|
for (int i = 0; i < rows.size(); i++) {
|
XWPFTableRow row = rows.get(i);
|
for (int j = 0; j < row.getTableCells().size(); j++) {
|
XWPFTableCell cell = row.getTableCells().get(j);
|
String text = cell.getText();
|
if (tableExpression.equals(text)) {
|
startRowIndex = i;
|
break rows;
|
}
|
|
}
|
}
|
if (startRowIndex == -1) {
|
return;
|
}
|
|
//在表格中查找子表字段以{{$开头}}以}}结尾的内容
|
String regex = "\\{\\{\\$[a-zA-Z0-9_]+\\}\\}";
|
Pattern pattern = Pattern.compile(regex);
|
//字段所在行
|
XWPFTableRow fieldRow = null;
|
for (int i = startRowIndex; i < rows.size(); i++) {
|
XWPFTableRow row = rows.get(i);
|
for (int j = 0; j < row.getTableCells().size(); j++) {
|
XWPFTableCell cell = row.getTableCells().get(j);
|
String text = cell.getText();
|
Matcher matcher = pattern.matcher(text);
|
if (matcher.find()) {
|
fieldRow = row;
|
i = rows.size();
|
break;
|
}
|
}
|
}
|
//删除起始行
|
xwpfTable.removeRow(startRowIndex);
|
if (fieldRow == null) {
|
return;
|
}
|
//获取字段所在行的索引
|
int fieldRowIndex = xwpfTable.getRows().indexOf(fieldRow);
|
//删除起始行到字段所在行之间的所有行
|
xwpfTable.removeRow(fieldRowIndex);
|
|
}
|
}
|