java读取word文件转html

借助第三方jar包实现

pom.xml

cpp 复制代码
<dependency>
	<groupId>com.aspose</groupId>
	<artifactId>aspose-words</artifactId>
	<version>15.12.0</version>
	<classifier>jdk16</classifier>
</dependency>

如果pom.xml无法成功下载,可以通过以下方法:

  1. 下载jar包到本地。下载路径:https://releases.aspose.com/zh/words/java/
  2. 添加jar包到项目下。添加路径:项目根目录下的lib文件夹
  3. pom.xml中引用jar包
cpp 复制代码
<dependency>
	<groupId>com.aspose.words</groupId>
	<artifactId>aspose-words</artifactId>
	<version>15.12.0</version>
	<scope>system</scope>
	<systemPath>${project.basedir}/lib/aspose-words-15.12.0-jdk16.jar</systemPath>
</dependency>

实现代码

cpp 复制代码
package com.example.demo.handler;

import com.alibaba.fastjson.JSONObject;
import com.aspose.words.HtmlSaveOptions;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.util.*;

@Component
public class WordAnalysis {
    /**
     * 解析word
     * @param multipartFile 前端接收的文件,根据自己的需求也可以将MultipartFile转换为File
     * @return TitleTreeVO 存放标题的实体
     */
    public List wordAnalysis(MultipartFile multipartFile) throws IOException {
        byte[] byteArr = multipartFile.getBytes();
        InputStream inputStream = new ByteArrayInputStream(byteArr);
        List tableList = new ArrayList();
        try {
            // 设置转化的格式
            HtmlSaveOptions saveOptions = new HtmlSaveOptions();
            saveOptions.setExportImagesAsBase64(false);
            // 将所有word中的图片放在临时文件夹中,并将html中的链接替换为临时文件夹中绝对路径
            String property = System.getProperty("java.io.tmpdir");
            saveOptions.setImagesFolder(property);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            // 把流转化为Document
            com.aspose.words.Document doc = new com.aspose.words.Document(inputStream);
            doc.save(baos, saveOptions);
            // 将html文件转化为Document,方便后续使用jsoup的操作
            Document htmlDoc = Jsoup.parse(baos.toString());
            // 解析Document
            tableList = analysisDoc(htmlDoc);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            inputStream.close();
        }
        return tableList;
    }

    /**
     * 解析Document,按需写,样例只写了表格处理
     * @param htmlDoc
     * @return
     */
    public List analysisDoc(Document htmlDoc) {
        Elements tables = htmlDoc.getElementsByTag("table");
        List tableList = new ArrayList();
        for (int i = 0; i < tables.size(); i++) {
            Map<String, Object> tableInfo = new HashMap<>();
            UUID uuid = UUID.randomUUID();
            Element table = tables.get(i);
//            String tableName = table.previousElementSibling().text();
//            if ("".equals(tableName)) {
//                tableName = table.nextElementSibling().text();
//            }
            tableInfo.put("tableId", uuid);
            tableInfo.put("tableName", "表"+(i+1));
            tableInfo.put("tableHtml", tables.get(i).toString());
            Elements rows = table.select("tr");
            List rowList = new ArrayList();
            for (Element row: rows) {
                if (!row.attributes().get("style").contains("height:0pt")) {
                    List rowInfo = new ArrayList();
                    Elements cells = row.select("td");
                    for (Element cell: cells) {
                        JSONObject cellInfo = new JSONObject();
                        String data = cell.text();
                        int rowspan = new Integer(cell.attributes().get("rowspan")=="" ? "1" : cell.attributes().get("rowspan"));
                        int colspan = new Integer(cell.attributes().get("colspan")=="" ? "1" : cell.attributes().get("colspan"));
                        System.out.print(data + "\t");
                        cellInfo.put("content", data);
                        cellInfo.put("rowspan", rowspan);
                        cellInfo.put("colspan", colspan);
                        rowInfo.add(cellInfo);
                    }
                    System.out.println();
                    rowList.add(rowInfo);
                }
            }
            tableInfo.put("tableContent", rowList);
            tableList.add(tableInfo);
        }
        return tableList;
    }
}
相关推荐
渣哥2 分钟前
Java CyclicBarrier 详解:原理、使用方式与应用场景
java
杨杨杨大侠8 分钟前
打开 JVM 黑匣子——走进 Java 字节码(一)
java·jvm·agent
SimonKing9 分钟前
接口调用总失败?试试Spring官方重试框架Spring-Retry
java·后端·程序员
咖啡Beans10 分钟前
SpringCloud网关Gateway功能实现
java·spring cloud
杨杨杨大侠12 分钟前
Atlas Mapper 案例 01:初级开发者 - 电商订单系统开发
java·开源·github
华仔啊12 分钟前
Java 8都出了这么多年,Optional还是没人用?到底卡在哪了?
java
用户0915 分钟前
Gradle Cache Entries 深度探索
android·java·kotlin
叽哥36 分钟前
Kotlin学习第 9 课:Kotlin 实战应用:从案例到项目
android·java·kotlin
糖糖TANG37 分钟前
从零开始制作我的第一个静态网页——教师节主题首页开发记录
html
阿杆1 小时前
同事嫌参数校验太丑,我直接掏出了更优雅的 SpEL Validator
java·spring boot·后端