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;
}
Java读取Word关键字工具类
最新推荐文章于 2024-07-26 16:03:13 发布