+-

我正在尝试阅读word文档模板,然后使用用户给定的数据替换模板中的变量,而没有像tempate那样更改标题或样式.我不确定我的工作是否正确,但是这是我开始的方式:
'XWPFDocument docx = new XWPFDocument(
new FileInputStream(
"D://TestDocumentPrep/src/XXXXX_TestReport_URL_Document.docx"));
XWPFWordExtractor we = new XWPFWordExtractor(docx);
String textData = we.getText();
String newTestData=textData.replace("$var_source_code$", list.get(1))
.replace("$var_rsvp_code$", list.get(2))
.replace("$var_ssn$", list.get(3))
.replace("$var_zip_code$", list.get(4))
.replace("$var_point_for_business$",
anotherData.getPointForBusiness())
.replace("$var_E1_url$", anotherData.getE1url())
.replace("$var_E2_url$", anotherData.getE2url())
.replace("$var_E3_url$", anotherData.getE3url());
System.out.println(newTestData);'
这就是我所做的,但是它将Word文档的内容作为字符串读取并替换了变量.现在如何将替换后的字符串以模板格式放入Word文档中?
Here I found something but Not exactly my solution
Here also I found something but not exact solution
最佳答案
嗨,我能够找到解决方案
这是我用于编辑Word文档的代码,它与要编辑的.doc和.docx格式的文件都很好,我想在不更改基本模板的情况下编辑并生成已编辑的新Word文档.
public void wordDocProcessor(AnotherVO anotherData, ArrayList<String> list,
String sourse, String destination) throws IOException,
InvalidFormatException {
XWPFDocument doc = new XWPFDocument(OPCPackage.open(sourse
+ "XXXXX_TestReport_URL_Document.doc"));
for (XWPFTable tbl : doc.getTables()) {
for (XWPFTableRow row : tbl.getRows()) {
for (XWPFTableCell cell : row.getTableCells()) {
for (XWPFParagraph p : cell.getParagraphs()) {
for (XWPFRun r : p.getRuns()) {
String text = r.getText(0);
if (text != null
&& text.contains("var_source_code")) {
text = text.replace("var_source_code",
list.get(1));
r.setText(text, 0);
}
if (text != null && text.contains("var_rsvp_code")) {
text = text.replace("var_rsvp_code",
list.get(2));
r.setText(text, 0);
}
if (text != null && text.contains("var_ssn")) {
text = text.replace("var_ssn", list.get(3));
r.setText(text, 0);
}
if (text != null && text.contains("var_zip_code")) {
text = text
.replace("var_zip_code", list.get(4));
r.setText(text, 0);
}
if (text != null
&& text.contains("var_point_for_business")) {
text = text.replace("var_point_for_business",
anotherData.getPointForBusiness());
r.setText(text, 0);
}
if (text != null && text.contains("var_E1_url")) {
text = text.replace("var_E1_url",
anotherData.getE1url());
r.setText(text, 0);
}
if (text != null && text.contains("var_E2_url")) {
text = text.replace("var_E2_url",
anotherData.getE2url());
r.setText(text, 0);
}
if (text != null && text.contains("var_E3_url")) {
text = text.replace("var_E3_url",
anotherData.getE3url());
r.setText(text, 0);
}
}
}
}
}
}
doc.write(new FileOutputStream(destination + list.get(0)
+ "_TestReport_URL_Document.doc"));
}
点击查看更多相关文章
转载注明原文:java-使用Apache POI编辑Word文档 - 乐贴网