4

我有一个 docx 模板,我将其保存为 .xml,然后解析内容。然后我正在生成一个新的更新的 Word 文档。生成word文档后,我无法打开它。它说“文件损坏”。我按确定。然后它说“如果你想检索文档,请按 OK”。我按确定。然后我得到更新的文件。每次都会发生这种情况。我创建了与独立 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();

}
4

4 回答 4

1

您可以使用 POI 或docx4j来确保创建有效的 Word 文档。

于 2011-05-14T08:38:59.290 回答
1

我使用 POI 库来生成 Word 文档(.doc,不是 .docx,但它也应该可以工作)。使用 POI,您可以: - 打开您的 Word 文档 - 使用干净的 API 编辑您想要的任何内容(不要在 XML 中搞砸) - 编写结果

http://poi.apache.org/

于 2011-01-07T11:39:56.063 回答
0

我已经广泛使用了 Apache POI 和 docx4j,并且已经说过 docx4j 更强大,因为它不仅为文档本身提供了更多开箱即用的支持,而且还为表格和图像提供了更多支持。docx4j 所做的很多工作都是自动化的,在 Apache 的 POI 领域,您必须为 docx 支持进行大量手动编码。不幸的是,对于 POI 的 docx 支持并没有做太多工作。我建议使用 docx4j,因为它们对打开和保存新的 .docx 文件有原生支持。

于 2013-05-10T15:47:06.410 回答
0

你检查过JVM的编码吗?我遇到了这个问题,最后我发现在 Eclipse 中我有 UTF-8,但在独立时我没有指定编码,所以 JVM 采用 ISO-8559。

请用参数检查它-Dfile.encoding=UTF-8

于 2012-04-02T14:45:29.913 回答