【发布时间】:2019-02-08 11:08:34
【问题描述】:
我需要打开一个 .dotx 文档,修改内容(或类似内容)并放入我自己的数据,然后返回生成的 .docx/document。
以dotx文件为例,在生成的docx文件中,字符串“name”应替换为“John”。
public static void main( String[] args ) throws IOException
{
String inputFile="D:/Copies 2.dotx";
// String outputeFile="D:/test.txt";
String outputeFile="D:/test.docx";
File inFile=new File(inputFile);
File ouFile=new File(outputeFile);
Map<String,String> hm = new HashMap<String,String>();
hm.put("Namur","Youssef");
App a = new App();
a.changeData(inFile,ouFile, hm);
}
private void changeData(File targetFile,File out, Map<String,String> substitutionData) throws IOException{
BufferedReader br = null;
String docxTemplate = "";
try {
br = new BufferedReader(new InputStreamReader(new FileInputStream(targetFile)));
String temp;
while( (temp = br.readLine()) != null) {
docxTemplate = docxTemplate + temp;
}
br.close();
}
catch (IOException e) {
br.close();
throw e;
}
Iterator<Entry<String, String>> substitutionDataIterator = substitutionData.entrySet().iterator();
while(substitutionDataIterator.hasNext()){
Map.Entry<String,String> pair = (Map.Entry<String,String>)substitutionDataIterator.next();
if(docxTemplate.contains(pair.getKey())){
if(pair.getValue() != null)
docxTemplate = docxTemplate.replace(pair.getKey(), pair.getValue());
else
docxTemplate = docxTemplate.replace(pair.getKey(), "NEDOSTAJE");
}
}
FileOutputStream fos = null;
try{
fos = new FileOutputStream(out);
fos.write(docxTemplate.getBytes());
fos.close();
}
catch (IOException e) {
fos.close();
throw e;
}
}
有人可以给我一些建议吗?
Ps:我使用的是 apach POI 3.16
【问题讨论】:
-
您认为您在当前代码中使用了哪些
apache poi类? -
是的,确实在这段代码中我没有使用 apache POI,它运行和编译正确但是当我尝试打开它时输出文件给我这个错误“我们很抱歉我们无法打开你的test1 因为我们发现内容有问题”,我想知道是否有办法使用 POI 用 java 替换 word 模板文档中的内容。
-
首先要知道:
*.dotx文件是什么?它只是一个文本文件吗?不,它是 Office Open XML 格式的文件,它是一个 ZIP 存档,包含一个特殊的目录结构,其中存储了不同的其他文件(主要是 XML 文件)。所以你不能像文本文件那样简单地处理它。这就是apache poi的用途。 -
第二件要知道的事:
*.dotx和*.docx文件有什么区别?主要是内容类型。因此,在读取*.dotx然后保存*.docx时,您还需要更改文件中的内容类型设置。见stackoverflow.com/questions/54377200/…。 -
@AxelRichter 非常感谢,我认为你是对的我应该先转换它!
标签: java apache-poi docx