在 Java 中以编程方式将 HTML/MXML 文件转换为 Word 文档

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6786062/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 17:15:51  来源:igfitidea点击:

Convert HTML/MXML file to Word doc programmatically in Java

javahtmlmxmldocx

提问by jennifer

I would like to convert either an HTML or MXML file document to Microsoft .doc and/or .docx format.

我想将 HTML 或 MXML 文件文档转换为 Microsoft .doc 和/或 .docx 格式。

Please provide an example for doing this?

请提供一个这样做的例子?

回答by jkraybill

I've found that by far the best (free) option to do conversions like this is to use the OpenOffice API. It has a very robust conversion facility. It's a bit of a pain to initially get working because of how abstract the API is, but once you do, it's powerful. This API wrapperhelps to simplify it somewhat.

我发现迄今为止进行此类转换的最佳(免费)选项是使用 OpenOffice API。它有一个非常强大的转换设施。由于 API 的抽象程度,最初开始工作有点痛苦,但是一旦你这样做了,它就会变得强大。这个 API 包装器有助于在某种程度上简化它。

回答by PVR

You can also use docx4j.jarwhich simply converts xhtml to docx.

您还可以使用docx4j.jar,它只是将 xhtml 转换为 docx。

You can save your format information as xhtml template and place input from form (like name,age,address etc) into the template at runtime.

您可以将格式信息保存为 xhtml 模板,并在运行时将来自表单的输入(如姓名、年龄、地址等)放入模板中。

This is a sample code to refer from this link

这是从此链接中引用的示例代码

public static void main(String[] args) throws Exception 
 {
        String xhtml= 
                "<table border=\"1\" cellpadding=\"1\" cellspacing=\"1\" style=\"width:100%;\"><tbody><tr><td>test</td><td>test</td></tr><tr><td>test</td><td>test</td></tr><tr><td>test</td><td>test</td></tr></tbody></table>";       

        // To docx, with content controls
        WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.createPackage();

        XHTMLImporterImpl XHTMLImporter = new XHTMLImporterImpl(wordMLPackage);

        wordMLPackage.getMainDocumentPart().getContent().addAll( 
                XHTMLImporter.convert( xhtml, null) );

        wordMLPackage.save(new java.io.File("D://sample.docx"));
}

回答by uris

You can use both iText and Apache POI to handle and convert MS doc in Java.

您可以使用 iText 和 Apache POI 来处理和转换 Java 中的 MS doc。