首页 > 编程语言 > 详细

java 替换word中占位符\标签 ${}内容

时间:2021-06-29 00:34:07      阅读:114      评论:0      收藏:0      [点我收藏+]

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();
        }
    }
 
}
 
 

 

java 替换word中占位符\标签 ${}内容

原文:https://www.cnblogs.com/romantic-321/p/14945754.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!