1. 程式人生 > 其它 >java 替換word中佔位符\標籤 ${}內容

java 替換word中佔位符\標籤 ${}內容

1、先看效果圖

原始檔案:

結果:

程式碼:

package com.test.wordTest;
 
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.CharacterRun;
import org.apache.poi.hwpf.usermodel.Paragraph;
import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.hwpf.usermodel.Section;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
 
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.HashMap; import java.util.Map; /** * @author * @Description * @date 2021/6/28 17:00 */ public class AsposeTest { public static void main(String[] args) { String filePath
= "C:\\勞動合同(標準版).docx"; POIFSFileSystem fs = null; try { fs = new POIFSFileSystem(new FileInputStream(filePath)); HWPFDocument doc = new HWPFDocument(fs); //將需要替換的內容翻到map中,如果word中使用的不是${}形式,map的可以也需要修改 Map<String,String> map = new HashMap<>(); map.put(
"${甲方蓋章}","急急急"); map.put("${乙方簽名}","煩煩煩"); map.put("${工作崗位}","java開發"); map.put("${工作地點}","北京朝陽"); replaceText(doc,map); saveWord(filePath, doc); } catch(FileNotFoundException e){ e.printStackTrace(); } catch(IOException e){ e.printStackTrace(); } } private static HWPFDocument replaceText(HWPFDocument doc, Map<String,String> map){ Range r1 = doc.getRange(); for (int i = 0; i < r1.numSections(); ++i ) { Section s = r1.getSection(i); for (int x = 0; x < s.numParagraphs(); x++) { Paragraph p = s.getParagraph(x); for (int z = 0; z < p.numCharacterRuns(); z++) { CharacterRun run = p.getCharacterRun(z); String text = run.text(); map.forEach((key,value) -> { if(text.contains(key)) { run.replaceText(key, value); } }); } } } return doc; } private static void saveWord(String filePath, HWPFDocument doc) throws FileNotFoundException, IOException { FileOutputStream out = null; try{ out = new FileOutputStream(filePath); doc.write(out); } finally{ out.close(); } } }