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




}
相关推荐
wujian83112 小时前
AI手机版怎么直接生成word?用“AI 导出鸭”把碎片时间变成专业文档
人工智能·ai·chatgpt·智能手机·word·ai导出鸭
鲲穹AI种草4 小时前
多文档批量整理如何选?多款 Word 处理工具能力客观记录
word·文档处理
AI英德西牛仔6 小时前
Claude导出word指令的PC端最优解:AI导出鸭电脑版底层逻辑全拆解
人工智能·word·excel·deepseek·ai导出鸭
Am-Chestnuts6 小时前
DeepSeek公式怎么复制到Word?用DS随心转保留LaTeX并生成可编辑文档
word
灯澜忆梦7 小时前
【基于GO的Web开发4】html/template 模板语法
后端·golang·html
AI导出鸭8 小时前
怎么让Grok做表格?AI导出鸭苹果版通过专属解析引擎,将Grok输出的管道表格智能还原为二维结构,一键导出Excel或Word标准表格。
人工智能·chatgpt·word·excel·ai导出鸭
我变秃了也没变强10 小时前
standalone模式部署flink集群
flink·apache
SelectDB技术团队10 小时前
15 分钟搭建 PostgreSQL + Apache Iceberg + Apache Doris 的湖仓分析平台
数据库·postgresql·apache
IMPYLH10 小时前
HTML 的 <html> 元素
前端·javascript·html