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




}
相关推荐
可涵不会debug14 分钟前
时序数据库选型指南:以Apache IoTDB为核心的大数据解决方案
apache·时序数据库·iotdb
不坑老师2 小时前
小工具显出大才能——不坑盒子为教育数字化转型贡献“新方案”
microsoft·word·excel·ppt·office
骆驼爱记录2 小时前
Python程序打包全攻略
自动化·word·excel·wps·新人首发
安小牛2 小时前
Apache License 2.0的中文介绍及其许可使用
笔记·apache
松涛和鸣3 小时前
55、ARM与IMX6ULL入门
c语言·arm开发·数据库·单片机·sqlite·html
Web项目开发4 小时前
静态企业 官网 html 模板,复制粘贴即可使用,适合快速搭建
css·html·css3
float_六七5 小时前
HTML5语义标签:section的正确用法
前端·html·html5
骆驼爱记录5 小时前
Excel绿色箭头秒消指南
开发语言·自动化·word·新人首发
世界唯一最大变量5 小时前
自创公式弄的自创AⅠ
html
鸽芷咕5 小时前
时序数据库选型指南:Apache IoTDB为何成大数据场景优选
apache·时序数据库·iotdb