使用Apache POI将Word转HTML

java 复制代码
package com.shengun.utils;


import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.w3c.dom.Document;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;

public class WordToHtmlTable {


    public static void main(String[] args) throws Exception {
        String path = "C:/Users/28916/Desktop/aaa/";
        try {
            convertToHtml(path + "a.doc", path + "sample.html");
            System.out.println("Word to HTML conversion successful!");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 使用Apache POI将Word转HTML
     * @param docFilePath
     * @param htmlFilePath
     * @throws Exception
     */
    public static void convertToHtml(String docFilePath, String htmlFilePath) throws Exception {
        InputStream input = new FileInputStream(new File(docFilePath));
        HWPFDocument wordDocument = new HWPFDocument(input);
        WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(
                DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());
        wordToHtmlConverter.processDocument(wordDocument);

        Document htmlDocument = wordToHtmlConverter.getDocument();
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        DOMSource domSource = new DOMSource(htmlDocument);
        StreamResult streamResult = new StreamResult(out);

        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer serializer = tf.newTransformer();
        serializer.setOutputProperty("encoding", "UTF-8");
        serializer.setOutputProperty("indent", "yes");
        serializer.setOutputProperty("method", "html");
        serializer.transform(domSource, streamResult);

        out.close();

        OutputStream outputStream = new FileOutputStream(htmlFilePath);
        outputStream.write(out.toByteArray());
        outputStream.close();
    }




}
相关推荐
路光.1 小时前
ReferenceError:Can‘t find variable:structureClone
前端·javascript·html·vue2
为美好的生活献上中指2 小时前
本地虚拟机部署redis集群
前端·redis·ubuntu·bootstrap·html·redis集群
SuperherRo3 小时前
服务攻防-中间件安全&Apache&Tomcat&Jetty&Weblogic&AJP协议&反序列化&CVE漏洞
中间件·tomcat·apache·jetty·weblogic
Komorebi_99993 小时前
前端开发|18 个高频易错知识点汇总(HTML+CSS+JS+Vue)面试 & 开发通用
javascript·css·html
dbkx_293 小时前
Word域操作记录(从2开始的公式编号排版)
word
要不枉此行4 小时前
【Python 实战】一键爬取 HTML 文档并合并为完整 PDF
python·pdf·html
Metaphor6924 小时前
使用 Python 查找并替换 Word 文档中的文本
python·c#·word
蒋胜山6 小时前
Word 练习题(6)
经验分享·word
djk88886 小时前
html table 分组合并 与导出分组后的数据
前端·html
回忆2012初秋7 小时前
时序库.net平台下的推荐 SonnetDB,一文分析清除他与Apache IoTDB的区同
apache·iotdb