docx4j 替换文本

  采用docx4j 替换word模板内容,并输出进行保存文件。

模板截图如下:



 

替换后截图如下:



  

模板制作过程中需要注意:

  1. 模板变量使用${}包含;
  2. 使用解压工具打开模板/word/document.xml文件。采用网上的xml格式化工具进行排版。进行整理。



 

代码如下:可在附件中下载。

 

import java.util.HashMap;

import org.docx4j.model.datastorage.migration.VariablePrepare;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart;

public class MyExampleReplaceText {

	private static final  String tale_templetate_docx  = "\\myexamples\\replace_text_templetate.docx";
	
	private static final  String tale_output_docx  = "\\myexamples\\replace_text__output.docx";
	
	public static void main(String[] args) throws Exception {
		//加载模板
		WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage
				.load(new java.io.File(System.getProperty("user.dir")+tale_templetate_docx));
		//数据替换预处理,调用API包
		VariablePrepare.prepare(wordMLPackage);
		//准备数据
		HashMap<String, String> mappings = new HashMap<String, String>();
		mappings.put("username", "张三");
		mappings.put("party_date", "2014年10月25日");
		mappings.put("numberCount", "150");
		mappings.put("pay_acount", "99.50");
		mappings.put("now_date", "2014年09月25日");
		
		//进行数据合并
		MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();
		documentPart.variableReplace(mappings);
		
		//保存文件
		String filename = System.getProperty("user.dir") + tale_output_docx;
		wordMLPackage.save(new java.io.File(filename) );
	}
}

 注意 此处的 签名,最好是导入到模板 压缩 包里 ,指定图片位置 。



 又更新 ,将表格替换也放到里面了

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值