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




}
相关推荐
htzyl2067 小时前
前端样式-弹窗淡入淡出,为什么你的 `transition` 一直不生效
前端·css·html
zhanlang02179 小时前
HTML 零基础入门到企业实战【第七章 7.5】表单验证基础属性:required、maxlength、placeholder
前端·html
AI英德西牛仔14 小时前
智谱清言导出word指令失效?PC端深度用户正在用“AI导出鸭”重构内容归档流
人工智能·重构·word·excel·deepseek·ai导出鸭
SEO_juper1 天前
Node.js 全站 SEO 体检报告生成器:一次查完标题、描述、canonical、H1、图片
开发语言·前端·node.js·html·bash
zhanlang02171 天前
HTML 零基础入门到企业实战【第七章 7.2】form 标签属性:action、method、name、target 详解
前端·html
feixing_fx2 天前
CSS 变量(Custom Properties):构建可扩展的主题切换系统
前端·css·前端框架·html·css3
木头左3 天前
【Node.js】Markdown 转带图片 Word 文档实战:docx 库转换器设计与 5 个踩坑
node.js·word·markdown·文档自动化
zhanlang02173 天前
HTML 零基础入门到企业实战【第七章 表单标签|7.1 表单核心作用:数据收集、用户交互原理】
前端·html·交互
思特奇时空智能3 天前
大规模点要素地图渲染性能优化实践
vue.js·arcgis·性能优化·node.js·html·gis·webgl
Brookty3 天前
HTML基础知识:表格布局、表单数据提交、元素标识与资源相对路径
前端·html