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




}
相关推荐
sayamber4 小时前
Nginx + Docker部署个人博客,从零到上线完整教程(2026最新版)
html
STRUGGLE_xlf4 小时前
AI大模型生成表格粘贴到 Word 后出现双线边框的原因与解决方案
word
weixin_416660074 小时前
2026 年 AI 对话转 Word 工具分析:Pandoc、Typora、aitoword 怎么选
人工智能·word
榴莲omega4 小时前
第12天:CSS(一)| Flexbox 布局完全指南
前端·css·html·js八股
fqrj20264 小时前
企业官网如何设计?专业公司网站设计制作要点解析
css·html·网站建设·网站开发
阿捞25 小时前
在 .NET 中使用 Moonshot Kimi + AgentFramework:从 SDK 到 Agent 的完整实践
html·.net·xhtml
路baby5 小时前
Pikachu安装过程中常见问题(apache和MySQL无法正常启动)
计算机网络·mysql·网络安全·adb·靶场·apache·pikachu
努力打怪升级6 小时前
Apache HTTP Server 2.4 Windows 版完整配置与运维手册
运维·http·apache
Reisentyan6 小时前
[vue3]HTML Learn Data Day 9
前端·vue.js·html
希望永不加班6 小时前
SpringBoot 邮件发送:文本邮件与 HTML 邮件
java·spring boot·后端·spring·html