java 替換docx文件中的字符串方法實(shí)現(xiàn)
替換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\\簡(jiǎn)歷.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);
}
到此這篇關(guān)于java 替換docx文件中的字符串方法實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)java 替換docx字符串內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
基于java實(shí)現(xiàn)DFA算法代碼實(shí)例
這篇文章主要介紹了基于java實(shí)現(xiàn)DFA算法代碼實(shí)例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-09-09
springboot動(dòng)態(tài)定時(shí)任務(wù)的實(shí)現(xiàn)方法示例
這篇文章主要給大家介紹了關(guān)于springboot動(dòng)態(tài)定時(shí)任務(wù)的實(shí)現(xiàn)方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-02-02
利用Java實(shí)現(xiàn)更改Word中的頁(yè)面大小和頁(yè)面方向
這篇文章主要為大家詳細(xì)介紹了一種高效便捷的方法——通過(guò)Java應(yīng)用程序,以編程方式更改Word中的頁(yè)面大小和頁(yè)面方向,感興趣的可以了解一下2023-03-03
Springboot整合Swagger2和Swagger3全過(guò)程
這篇文章主要介紹了Springboot整合Swagger2和Swagger3全過(guò)程,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-07-07
Java方法參數(shù)傳遞如何實(shí)現(xiàn)
這篇文章主要介紹了Java方法參數(shù)傳遞如何實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-05-05

