Java poi word模板填充数据
1、明细表格式 ${list_xxxxx} 普通格式 ${xxxxxx}
2、replaceInTable方法中 table.removeRow(2); 第三行是明细数据的第一行
工具类
public class WordOperationUtil {
public void replaceWordContext(XWPFDocument doc, List<Map<String, Object>> params) throws InvalidFormatException, IOException, XmlException {
replaceInHeader(doc, params);
replaceInTable(doc, params);
replaceInPara(doc, params);
}
public void replaceInPara(XWPFParagraph para, List<Map<String, Object>> params) throws InvalidFormatException, FileNotFoundException {
if (this.matcher(para.getParagraphText()).find()) {
List<XWPFRun> runs = para.getRuns();
if (runs.size() == 0) {
return;
}
String text = "";
for (int i = 0; i < runs.size(); i++) {
text += runs.get(i).text();
}
for (int i = 1; i < runs.size(); i++) {
para.removeRun(i);
}
String outStr = getStrings(text, params.get(0));
XWPFRun runX = para.getRuns().get(0);
runX.setText(outStr, 0);
}
}
public void replaceInParaList(XWPFParagraph para, String params) throws InvalidFormatException, FileNotFoundException {
List<XWPFRun> runs = para.getRuns();
if (runs.size() == 0) {
return;
}
for (int i = 1; i < runs.size(); i++) {
para.removeRun(i);
i--;
}
XWPFRun runX = para.getRuns().get(0);
runX.setText(params, 0);
}
public String getStrings(String inStr, Map<String, Object> mapvalue) {
String outStr = inStr;
String regex = "\\$\\{(.*?)\\}";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(inStr);
while (m.find()) {
String ppStr = m.group(0);
String ppReslutStr = m.group(1);
outStr = strReplaceAll(outStr, ppStr, getMapValue(mapvalue, ppReslutStr));
}
return outStr;
}
public Map<String, Object> getListStrings(String inStr) {
Map<String, Object> outMap = new HashMap<>();
boolean out = false;
String regex = "\\$\\{list_(.*?)\\}";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(inStr);
while (m.find()) {
String ppReslutStr = m.group(1);
out = true;
outMap.put("filedName", ppReslutStr);
}
outMap.put("issuccess", out);
return outMap;
}
private String getMapValue(Map<String, Object> mapvalue, String key) {
String outStr = key;
if (mapvalue.containsKey(key)) {
outStr = mapvalue.get(key).toString();
}
return outStr;
}
private String strReplaceAll(String inStr, String target, String replacement) {
String outStr = inStr;
outStr = inStr.replace(target, replacement);
if (outStr.contains(target)) {
outStr = strReplaceAll(outStr, target, replacement);
}
return outStr;
}
public void replaceInTable(XWPFDocument doc, List<Map<String, Object>> params) throws InvalidFormatException, IOException, XmlException {
List<XWPFTable> xwpfTables = doc.getTables();
for (XWPFTable table : xwpfTables) {
replaceInTable(table, params);
}
}
public void replaceInTable(XWPFTable table, List<Map<String, Object>> params) throws InvalidFormatException, IOException, XmlException {
String text = table.getText();
boolean islist = (boolean) getListStrings(text).get("issuccess");
int i = 0;
List<XWPFTableRow> rows = table.getRows();
List<String> fileds = new ArrayList<>();
if (islist) {
for (int t = 0; t < rows.size(); t++) {
XWPFTableRow row = rows.get(t);
List<XWPFTableCell> cells = row.getTableCells();
for (XWPFTableCell cell : cells) {
String cellText = cell.getText();
boolean isListFiledName = (boolean) getListStrings(cellText).get("issuccess");
if (isListFiledName) {
String filedName = (String) getListStrings(cellText).get("filedName");
fileds.add(filedName);
i++;
}
}
if (i > 0) {
break;
}
}
for (int j = 0; j < params.size(); j++) {
CTRow ctrow = CTRow.Factory.parse(table.getRow(2).getCtRow().newInputStream());
XWPFTableRow newrow = new XWPFTableRow(ctrow, table);
List<XWPFTableCell> cells = newrow.getTableCells();
int t = 0;
for (XWPFTableCell cell : cells) {
List<XWPFParagraph> paras = cell.getParagraphs();
String value = "";
for (XWPFParagraph para : paras) {
value = params.get(j).get(fileds.get(t)).toString();
replaceInParaList(para, value);
}
t++;
}
table.addRow(newrow);
}
table.removeRow(2);
} else {
for (XWPFTableRow row : rows) {
List<XWPFTableCell> cells = row.getTableCells();
for (XWPFTableCell cell : cells) {
List<XWPFParagraph> paras = cell.getParagraphs();
for (XWPFParagraph para : paras) {
this.replaceInPara(para, params);
}
}
}
}
}
public void replaceInPara(XWPFDocument doc, List<Map<String, Object>> params) throws InvalidFormatException, FileNotFoundException {
Iterator<XWPFParagraph> iterator = doc.getParagraphsIterator();
while (iterator.hasNext()) {
XWPFParagraph para = iterator.next();
this.replaceInPara(para, params);
}
}
public void replaceInHeader(XWPFDocument doc, List<Map<String, Object>> params) throws InvalidFormatException, IOException, XmlException {
List<XWPFHeader> pageHeaders = doc.getHeaderList();
for (XWPFHeader pageHeader : pageHeaders) {
List<XWPFParagraph> paragraphs = pageHeader.getParagraphs();
List<XWPFTable> tables = pageHeader.getTables();
for (XWPFParagraph paragraph : paragraphs) {
this.replaceInPara(paragraph, params);
}
for (XWPFTable table : tables) {
this.replaceInTable(table, params);
}
}
}
private Matcher matcher(String str) {
Pattern pattern = Pattern.compile("\\$\\{(.+?)\\}", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(str);
return matcher;
}
public void close(InputStream is) {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void close(OutputStream os) {
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void replaceInPara0(XWPFParagraph para, Map<String, Object> params) throws InvalidFormatException, FileNotFoundException {
if (this.matcher(para.getParagraphText()).find()) {
List<XWPFRun> runs = para.getRuns();
for (int i = 0; i < runs.size(); i++) {
XWPFRun run = runs.get(i);
String runText = run.text();
if (matcher(runText).find()) {
String outStr = getStrings(runText, params);
run.setText(outStr, 0);
}
}
}
}
private void setTextStyle(XWPFRun runX, XWPFRun replace) {
runX.setCapitalized(replace.isCapitalized());
runX.setTextPosition(replace.getTextPosition());
runX.setStrike(replace.isStrike());
runX.setStrikeThrough(replace.isStrikeThrough());
runX.setEmbossed(replace.isEmbossed());
runX.setDoubleStrikethrough(replace.isDoubleStrikeThrough());
runX.setColor(replace.getColor());
runX.setFontFamily(replace.getFontFamily());
runX.setBold(replace.isBold());
runX.setFontSize(replace.getFontSize());
runX.setImprinted(replace.isImprinted());
runX.setItalic(replace.isItalic());
runX.setShadow(replace.isShadowed());
runX.setSmallCaps(replace.isSmallCaps());
runX.setSubscript(replace.getSubscript());
runX.setUnderline(replace.getUnderline());
}
public void replaceInPara2(XWPFParagraph para, Map<String, Object> params) throws InvalidFormatException, FileNotFoundException {
if (this.matcher(para.getParagraphText()).find()) {
List<XWPFRun> runs = para.getRuns();
String text = "";
for (int i = 0; i < runs.size(); i++) {
text += runs.get(i).toString();
}
String outStr = getStrings(text, params);
if (text.contains("$")) {
Object[] runArr = runs.toArray();
int $Index = 0;
for (int j = 0; j < runArr.length; j++) {
if (runArr[j].toString().contains("$")) {
$Index = j;
break;
}
}
int startIn = $Index;
while (startIn < runs.size()) {
para.removeRun(startIn);
}
para.createRun().setText(outStr);
}
}
}
}
2、方法调用
public static void main(String[] args) throws IOException, InvalidFormatException, XmlException {
List<Map<String, Object>> maplists =new ArrayList<>();
Map<String, Object> params0 = new HashMap<>();
params0.put("orderno", "1");
maplists.add(params0);
InputStream is = new FileInputStream(new File("C:\\Users\\xxxxx\\Desktop\\word\\temp.docx"));
XWPFDocument doc= new XWPFDocument(is);
WordOperationUtil wordOperationUtil = new WordOperationUtil();
wordOperationUtil.replaceWordContext(doc, maplists);
OutputStream os = new FileOutputStream(new File("C:\\Users\\xxxx\\Desktop\\word\\temp2.docx"));
doc.write(os);
wordOperationUtil.close(os);
wordOperationUtil.close(is);
os.flush();
os.close();
System.out.println("word成功生成");
}
模板格式
