Java读取Word关键字工具类

public static List<String> getWordKey(String templateUri) {
    String buffer = "";
    List<String> keyListFromString = null;
    String localPath = RuoYiConfig.getProfile() + StringUtils.substringAfter(templateUri, "/profile");
    try {
        OPCPackage opcPackage = POIXMLDocument.openPackage(localPath);
        POIXMLTextExtractor extractor = new XWPFWordExtractor(opcPackage);
        buffer = extractor.getText();
        keyListFromString = getKeyListFromString(buffer, "{{", "}}");
        opcPackage.close();
        return keyListFromString;
    } catch (Exception e) {
        log.error(e.getMessage());
        e.printStackTrace();
    }
    return keyListFromString;
}

/**
 * 查询一个字符串再另一个字符串中出现的下标
 *
 * @param str
 * @param key
 * @return
 */
public static List<Integer> searchAllIndex(String str, String key) {
    List<Integer> allIndex = new ArrayList<Integer>();
    int a = str.indexOf(key);
    while (a != -1) {
        allIndex.add(a);
        a = str.indexOf(key, a + 1);
    }
    return allIndex;
}

/**
 * 根据关键字 获取字符串中参数
 *
 * @param string
 * @param keyStart 如'${ * @param keyEnd 如 }'
 * @return
 */
public static List<String> getKeyListFromString(String string, String keyStart, String keyEnd) {
    // 返回数据
    List<String> allStringList = new ArrayList<String>();
    // 判断不为空
    if (StringUtils.isNotBlank(string)) {
        string = string.replaceAll("\\\\s*", "");
        // 开始keyIndex集合
        List<Integer> firstIndex = searchAllIndex(string, keyStart);
        // 结束keyIndex集合
        List<Integer> endIndex = searchAllIndex(string, keyEnd);
        // 不为空
        if (CollectionUtils.isNotEmpty(firstIndex)) {
            // 循环
            for (int i = 0; i < firstIndex.size(); i++) {
                // 截取关键字部分
                String temp = string.substring(firstIndex.get(i) + keyStart.length(), endIndex.get(i));
                // 添加到返回数据中
                allStringList.add(temp);
            }
        }
    }
    return allStringList;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值