【问题标题】:using WordToHtmlConverter converter in Apache POI在 Apache POI 中使用 WordToHtmlConverter 转换器
【发布时间】:2012-01-04 18:11:24
【问题描述】:
我正在尝试使用 WordToHtmlConverter 类转换 HTML 中的 word 文档,但文档不清楚。
WordToHtmlConverter 有一个采用 org.w3c.dom.Document 的构造函数,但我不认为它是 word 文档。
有没有人有关于如何加载word文档并将其转换为html的示例程序。
【问题讨论】:
标签:
java
ms-word
apache-poi
【解决方案1】:
您现在最好的选择可能是查看单元测试,例如TestWordToHtmlConverter。这将告诉你如何做到这一点
一般来说,您传入要填充的 xml 文档,让 WordToHtmlConverter 从 Word 文档生成 HTML,然后将 xml 文档转换为适当的输出(缩进、换行等)
您的代码可能看起来像:
Document newDocument = DocumentBuilderFactory.newInstance()
.newDocumentBuilder().newDocument();
WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(
newDocument );
wordToHtmlConverter.processDocument( hwpfDocument );
StringWriter stringWriter = new StringWriter();
Transformer transformer = TransformerFactory.newInstance()
.newTransformer();
transformer.setOutputProperty( OutputKeys.INDENT, "yes" );
transformer.setOutputProperty( OutputKeys.ENCODING, "utf-8" );
transformer.setOutputProperty( OutputKeys.METHOD, "html" );
transformer.transform(
new DOMSource( wordToHtmlConverter.getDocument() ),
new StreamResult( stringWriter ) );
String html = stringWriter.toString();