java解析word

1、加入POI依赖

<!--poi-->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>4.1.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>4.1.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-scratchpad</artifactId>
            <version>4.1.2</version>
        </dependency>

2、编码

import lombok.extern.slf4j.Slf4j;
import net.go2global.common.core.exception.CommonException;
import net.go2global.common.core.util.file.Go2GlobalFileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * word工具类
 * @Author zyh
 * @Date 2021/6/9 17:14
 */
@Slf4j
public class WordUtils {

    /**
     * 根据本地文件路径解析word文本内容
     * @param localFilePath
     * @return
     * @throws IOException
     */
    public static String resolve(String localFilePath) throws IOException {

        String fileSuffix = Go2GlobalFileUtils.getFileSuffix(localFilePath);
        if(StringUtils.isEmpty(fileSuffix)){
            throw new CommonException(CommonException.FILE_FORMAT_ERROR,"文件没有后缀!");
        }

        if(fileSuffix.equalsIgnoreCase(".doc")){
            return getDocText(localFilePath);
        }else if(fileSuffix.equalsIgnoreCase(".docx")){
            return getDocxText(localFilePath);
        }

        return null;
    }

    /**
     * 解析doc
     * @param localFilePath
     * @return
     * @throws IOException
     */
    private static String getDocText(String localFilePath) throws IOException {

        File file=new File(localFilePath);
        FileInputStream fis=new FileInputStream(file);

        HWPFDocument doc = new HWPFDocument(fis);
        Range rang = doc.getRange();
        String text = rang.text();
        fis.close();

        return text;
    }

    /**
     * 解析docx
     * @param localFilePath
     * @return
     * @throws IOException
     */
    private static String getDocxText(String localFilePath) throws IOException {

        File file=new File(localFilePath);
        FileInputStream fis=new FileInputStream(file);

        XWPFDocument doc = new XWPFDocument(fis);
        XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
        String text = extractor.getText();
        fis.close();

        return text;
    }

}

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值