在实际业务中需要使用JAVA的POI对Word中一段话中的日期上标进行处理,在网上没有找到合适的轮子
public void render(InputStream is, OutputStream os, HashMap<String, Object> data) { ZipSecureFile.setMinInflateRatio(-1.0d); log.debug("render docx..."); try { ConfigureBuilder builder = Configure.builder(); builder.buildGramer("«", "»"); XWPFTemplate render = XWPFTemplate.compile(is, builder.build()).render(data); NiceXWPFDocument xwpfDocument = render.getXWPFDocument(); List paras = xwpfDocument.getParagraphs(); //处理上标问题 String[] superArray = new String[]{"th", "nd", "st", "rd"}; List superList = Arrays.asList(superArray); String reg = "[0-9](th|nd|st|rd)"; Pattern pattern = Pattern.compile(reg); for (XWPFParagraph para : paras) { Matcher matcher = pattern.matcher(para.getText()); List<HashMap<String, HashMap<String, Object>>> list = new ArrayList<>(); String text = para.getText(); List runs = para.getRuns(); //获取样式 HashMap<String, Object> style = new HashMap<>(); for (XWPFRun run : runs) { if (Objects.nonNull(run.getText(0))) { style.put("fontFamily", run.getFontFamily()); style.put("bold", run.isBold()); style.put("fontSize", run.getFontSize() == -1 ? 12 : run.getFontSize()); } } int index = 0; String end = ""; while (matcher.find()) { String pre = matcher.group().substring(1); end = text.substring(text.lastIndexOf(pre) + 2); HashMap<String, HashMap<String, Object>> item = new HashMap<>(); String start = text.substring(index, text.indexOf(pre, index)); index = text.indexOf(pre, index) + 2; item.put(start, style); list.add(item); HashMap<String, HashMap<String, Object>> ThItem = new HashMap<>(); ThItem.put(pre, style); list.add(ThItem); } if (!end.isEmpty()) { HashMap<String, HashMap<String, Object>> item = new HashMap<>(); item.put(end, style); list.add(item); } if (list.size() > 0) { //清空段落内容 for (XWPFRun run : runs) { run.setText("", 0); } //填充段落内容 for (HashMap<String, HashMap<String, Object>> stringHashMapHashMap : list) { for (Map.Entry<String, HashMap<String, Object>> stringHashMapEntry : stringHashMapHashMap.entrySet()) { XWPFRun endRun = para.createRun(); endRun.setText(stringHashMapEntry.getKey()); endRun.setFontFamily((String) stringHashMapEntry.getValue().get("fontFamily")); endRun.setFontSize((Integer) stringHashMapEntry.getValue().get("fontSize")); endRun.setBold((Boolean) stringHashMapEntry.getValue().get("bold")); if (superList.contains(stringHashMapEntry.getKey())) { endRun.setSubscript(VerticalAlign.SUPERSCRIPT); } } } } } xwpfDocument.write(os); // render.write(os); is.close(); os.close(); } catch (IOException e) { throw new ServiceException("render docx error:" + e.getMessage()); } log.debug("render docx success..."); }