我正在尝试阅读一个单词文档模板,然后用用户给定的数据替换模板中的变量。不用改变标题上的标题或样式。我不确定我在做什么是是否正确但这是我开始的方式:
Dictionary< Char, List<Int32> > map = new Dictionary< Char, List<Int32> >();
foreach(Pair<Char,Int32> entry in input) {
Char c = entry.First;
if( !map.ContainsKey( c ) ) {
map.Add( c, new List<Int32>() );
}
map[ c ].Add( entry.Second );
}
这就是我所做的。但是它将word文档的内容作为字符串读取并替换变量。现在如何将替换的字符串放在word文档中的模板格式中?
Here I found something but Not exactly my solution
Here also I found something but not exact solution
答案 0 :(得分:4)
您好我能找到解决方案
以下是我用来编辑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"));
}