这篇文章给大家介绍使用java怎么替换docx文件中的字符串,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。
替换docx文件里面的 ${} 字符串
public class Main {
public static void main(String[] args) throws Exception {
String template = "C:\\Users\\lzh\\Desktop\\模板.docx";
String outSrc = "C:\\Users\\lzh\\Desktop\\简历.docx";
var is = new FileInputStream(template);
var os = new FileOutputStream(outSrc);
editDocx(os, is, xml -> {
Map<String,String> map = new HashMap<>();
map.put("${name}", "李**");
map.put("${sex}", "男");
map.put("${age}", "21");
Pattern p = Pattern.compile("(\\$\\{)([\\w]+)(\\})");
Matcher m = p.matcher(xml);
StringBuffer sb = new StringBuffer();
while (m.find()) {
String group = m.group();
m.appendReplacement(sb, map.get(group));
}
m.appendTail(sb);
xml = sb.toString();
return xml;
});
}
public static void editDocx(OutputStream bos,InputStream is, Process process){
ZipInputStream zin = new ZipInputStream(is);
ZipOutputStream zos = new ZipOutputStream(bos);
try {
ZipEntry entry;
while((entry = zin.getNextEntry()) != null) {
//把输入流的文件传到输出流中 如果是word/document.xml由我们输入
zos.putNextEntry(new ZipEntry(entry.getName()));
if("word/document.xml".equals(entry.getName())){
String xml = new BufferedReader(new InputStreamReader(zin)).lines().collect(Collectors.joining(System.lineSeparator()));
xml = process.process(xml);
ByteArrayInputStream byteIn = new ByteArrayInputStream(xml.getBytes());
int c;
while ((c = byteIn.read()) != -1) {
zos.write(c);
}
byteIn.close();
}else {
int c;
while ((c = zin.read()) != -1) {
zos.write(c);
}
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
zos.close();
zin.closeEntry();
zin.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
interface Process {
String process(String xml);
}
关于使用java怎么替换docx文件中的字符串就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。