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




}
相关推荐
ZC跨境爬虫1 小时前
海南大学交友平台登录页开发实战day6(覆写接口+Flask 本地链接正常访问)
前端·后端·python·flask·html
iReachers5 小时前
HTML打包EXE三种加密方式对比:静态密码、离线一机一码、网络验证
html·html转exe·html打包exe·html一键打包exe工具
05Nuyoah5 小时前
第一阶段:HTML的笔记
前端·笔记·html
CodeCxil5 小时前
基于Vue的在线Online Word文档编辑器-效果预览
前端·vue.js·word
CodeCxil5 小时前
基于Vue的在线Online Word文档编辑器
vue.js·编辑器·word
Apache IoTDB6 小时前
Apache IoTDB V2.0.8 发布|新增模型并发推理,优化同步配置与安全加固
安全·apache·iotdb
蓝魔Y6 小时前
Apache—Kafka实践
分布式·kafka·apache
诸葛大钢铁6 小时前
如何将PDF以矢量图插入Word? 在线将PDF转为SVG格式
pdf·word·矢量图·pdf2svg
神仙别闹6 小时前
基于 MATLAB 实现 Word 的信息隐藏算法
c#·word·xhtml
华科大胡子1 天前
HTML头部元信息避坑
html