使用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();
    }




}
相关推荐
浪浪山小白兔7 小时前
HTML5 语义元素详解
前端·html·html5
追Star仙8 小时前
基于Qt中的QAxObject实现指定表格合并数据进行word表格的合并
开发语言·笔记·qt·word
五行星辰8 小时前
用 Java 发送 HTML 内容并带附件的电子邮件
java·html
wanfeng_099 小时前
视频m3u8形式播放 -- python and html
python·html·video·hls·m3u8
远方 hi10 小时前
linux虚拟机连接不上Xshell
开发语言·php·apache
哇哦Q11 小时前
原生HTML集合
前端·javascript·html
黄交大彭于晏13 小时前
C语言常用知识结构深入学习
c语言·学习·word
Faylynn14 小时前
Word常见问题:嵌入图片无法显示完整
word
浪浪山小白兔1 天前
HTML5 新表单属性详解
前端·html·html5
浪浪山小白兔1 天前
HTML5 常用事件详解
前端·html·html5