java 使用xml生成word_java 根据word xml模板生成word

这里用的是poi相关jar包以及freemarker插值技术实现,poi相关jar包这里不再述说

1,编辑word并保存为xml

82cff87993b95b027c32b6d8e5094368.png

2,把xml后缀改为ftl文件

3,前端代码

// alert(jsonStr);

var url = "${ctx}//exportWordXTOdsxdlsdbh.htm?jsonStr="+ jsonStr;

window.open(url, 'xxtitle');

4,后台代码

@RequestMapping("exportWordXTOgdlbh")

public void exportWordXTOgdlbh(HttpServletRequest request,HttpServletResponse response) throws Exception{

String str = request.getParameter("jsonStr");

//去掉单引号和双引号

str = str.replace("'", "");

str = str.replace("\"", "");

Map rootMap = new HashMap();

System.out.println(str);

Gson gson = new Gson();

rootMap = gson.fromJson(str, rootMap.getClass());

String name = "xxx--" + df.format(new Date()) + ".doc";

//设置MIMI类型,默认的是text/hmtl

response.setHeader("Content-Type", "application/msword");

//解决中文乱码,以及设置生成的文档名

response.setHeader("Content-Disposition", "attachment;filename="+ new String(name.getBytes("utf-8"), "ISO8859-1"));

//取得当前类所在的目录

String filePath = FileUtil.getClassesPath() + File.separator + "template"+ File.separator +"officeftl"+ File.separator +"zdjs";

Configuration cfg = new Configuration();

cfg.setDirectoryForTemplateLoading(new File(filePath));

//这里不设置编码的话,即是成功了有时也打不开文件,因为乱码

Template temp = cfg.getTemplate("exportWordXTOgdlbh.ftl","utf-8");

PrintWriter pw = response.getWriter();

/* 合并数据模型和模版*/

temp.process(rootMap, pw);

pw.flush();

pw.close();

}

5,注意事项

打开的xml要看看是否为途中¥{}的样式,如果被wold分割了,需要自己了解wold xml格式并去修改

26558f5908670064e9a25b142dbfd96c.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值