一段文字如下:
Confucius(孔子) _31_ Chinese teacher, editor, politician and philosopher of the Spring and Autumn period of _32_ history. Confucius(孔子) _33__ Chinese teacher, editor, politician and philosopher of the Spring and Autumn period of __34_ history.
需求是将其中的 _数字_ 格式替换为,即数字下划线格式
先看代码:
package com.my.utils;
import com.alibaba.fastjson.JSONObject;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.data.Paragraphs;
import com.deepoove.poi.data.TextRenderData;
import com.deepoove.poi.data.Texts;
import com.deepoove.poi.data.style.Style;
import com.deepoove.poi.policy.ParagraphRenderPolicy;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xwpf.usermodel.UnderlinePatterns;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* <pre>
* Description : word文档生成工具类
* @Author :kevy
* Date : 2021/8/19 0019 13:46
* Version : 1.0
* </pre>
*/
public class DocUtil {
public static final String SPT = "@@@";
public static final String UNDERLINE_RULE = "[_]+[\\d]+[_]+";
public static void main(String[] args) throws Exception {
String tplPath = "E:\\test.docx";
String outPath = "E:\\out.docx";
String t = "Confucius(孔子) _31_ Chinese teacher, editor, politician and philosopher of the Spring and Autumn period of _32_ history" +
".Confucius(孔子) _33__ Chinese teacher, editor, politician and philosopher of the Spring and Autumn period of __34_ history.";
Configure config = Configure.builder().bind("title", new ParagraphRenderPolicy()).useSpringEL(false).build();
JSONObject a = new JSONObject();
a.put("title", Paragraphs.of().addTexts(dealUnderlineText(t)).create());
XWPFTemplate template = XWPFTemplate.compile(tplPath, config).render(a);
template.writeAndClose(new FileOutputStream(outPath));
}
/**
* @Description 处理下划线文本
* @Author kevy
* @Date 2021/8/26 0026 11:57
* @param t
**/
public static List<TextRenderData> dealUnderlineText(String t) {
Matcher m = Pattern.compile(UNDERLINE_RULE).matcher(t);
List<String> items = new ArrayList<>();
while (m.find()) {
items.add(m.group());
}
for (String s : items) {
t = t.replace(s, SPT + s + SPT);
}
List<TextRenderData> list = new ArrayList<>();
String[] arr = t.split(SPT);
for (String s : arr) {
if (StringUtils.isNotBlank(s)) {
if (items.contains(s)) {
list.add(Texts.of(" " + s.replaceAll("_", "").replaceAll("\\s", "") + " ").style(
Style.builder().buildUnderlineColor("000000").buildUnderlinePatterns(UnderlinePatterns.SINGLE).build()).create());
} else {
list.add(Texts.of(s).create());
}
}
}
return list;
}
}
word模板格式如下:
生成效果如下: