java 替換docx文件中的字符串方法實現(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\\簡歷.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文件中的字符串方法實現(xiàn)的文章就介紹到這了,更多相關(guān)java 替換docx字符串內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
java實現(xiàn)漢字轉(zhuǎn)unicode與漢字轉(zhuǎn)16進制實例
這篇文章主要介紹了java實現(xiàn)漢字轉(zhuǎn)unicode與漢字轉(zhuǎn)16進制的實現(xiàn)方法,是Java操作漢字編碼轉(zhuǎn)換的一個典型應(yīng)用,非常具有實用價值,需要的朋友可以參考下2014-10-10
mybatis中insert返回值為1,但數(shù)據(jù)庫卻沒有數(shù)據(jù)
這篇文章主要介紹了mybatis中insert返回值為1,但數(shù)據(jù)庫卻沒有數(shù)據(jù),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-10-10
Java8的default和static關(guān)鍵字的使用講解
今天小編就為大家分享一篇關(guān)于Java8的default和static關(guān)鍵字的使用講解,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2019-01-01
Elasticsearch常見字段映射類型之scaled_float解讀
這篇文章主要介紹了Elasticsearch常見字段映射類型之scaled_float解讀。具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-11-11
IntelliJ IDEA : .java文件左下角顯示"J"圖標(biāo)的問題
IntelliJ IDEA : .java文件 左下角顯示“J”,并且不能執(zhí)行代碼,本文通過圖文并茂的形式給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友參考下吧2020-10-10
Spring操作JdbcTemplate數(shù)據(jù)庫的方法學(xué)習(xí)
這篇文章主要為大家介紹了Spring操作JdbcTemplate數(shù)據(jù)庫方法學(xué)習(xí),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-05-05

