我有一个 docx 模板,我将其保存为 .xml,然后解析内容。 然后我生成一个新的更新的 word 文档。 word文档生成后打不开。它说“文档损坏”。我按确定。然后它说“如果您想检索文档,请按确定”。我按确定。然后我得到更新的文件。每次都会发生这种情况。我创建了与独立 Java 应用程序相同的程序。通过独立 Java 应用程序生成的文档打开时没有任何错误。任何人都可以让我对此有所了解吗?我也在服务器端使用了相同的代码。
这是我用来生成文档的代码。
try {
// Prepare the DOM document for writing
Source source = new DOMSource(doc);
// Prepare the output file
FileOutputStream file = new FileOutputStream(filename);
Result result = new StreamResult(file);
// Write the DOM document to the file
Transformer xformer = TransformerFactory.newInstance()
.newTransformer();
xformer.transform(source, result);
file.close();
} catch (TransformerConfigurationException e) {
System.out.println("Transformation Configuration Excepiton in WriteXMLFile");
} catch (TransformerException e) {
System.out.println("Transformation Excepiton in WriteXMLFile");
} catch (Exception e) {
System.out.println("Transformation Excepiton in WriteXMLFile");
e.printStackTrace();
}
最佳答案
我使用 POI 库生成 Word 文档(.doc,不是 .docx,但它应该也可以)。 使用 POI,您可以: - 打开你的word文档 - 使用干净的 API 编辑任何你想要的东西(不要搞乱 XML) - 写入结果
关于java - 在java中生成docx,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2161438/