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




}
相关推荐
SouthRosefinch8 小时前
一、HTML简介与开发环境
开发语言·前端·html
倔强的石头1068 小时前
工业平台选型指南:权限、审计与多租户治理——用 Apache IoTDB 把“数据可用”升级为“数据可控”
人工智能·apache·iotdb
kyriewen9 小时前
别再滥用 iframe 了!这些场景下它其实是最优解
前端·javascript·html
optimistic_chen10 小时前
【Vue入门】创建Vue工程环境和响应式函数
前端·javascript·vue.js·前端框架·html
酉鬼女又兒11 小时前
HTML零基础快速入门篇(可用于备赛蓝桥杯Web应用开发) 牛客手把手戴刷FED1~8:基本标签,基本标签,媒体标签详解
前端·职场和发展·蓝桥杯·html·web
K姐研究社12 小时前
Nano Banana 2 国内使用教程:LiblibAI 免翻墙使用
前端·javascript·html
SeaTunnel13 小时前
Apache SeaTunnel 2.3.13 版本前瞻:核心引擎变化和 AI ETL 趋势值得关注
数据仓库·人工智能·apache·etl·seatunnel·数据同步
盘古工具14 小时前
告别重复劳动:Word 重复上一次操作的两种方法
windows·word
kyriewen15 小时前
盒模型:CSS 世界的物理法则,margin 塌陷与 padding 的恩怨情仇
前端·css·html
怪侠_岭南一只猿15 小时前
爬虫阶段三实战练习题二:使用 Selenium 模拟爬取拉勾网职位表
css·爬虫·python·selenium·html