java导出带图片的Word文档(freemarker)带图片

1.首先新建一个带图片的doc

 

2.另存为xml格式(具体看上一篇)

3.把生成的xml文件进行修改

4.修改后缀为ftl,作为模板文件使用,放到指定位置(我放到了电脑的D盘template文件夹中)

5.后台填充数据

Map<String, Object> data = new HashMap<String, Object>(); //声明map用来存数据

//将具体的数据存到map中,注意,这里的key名称要和模板文件的占位符名称一致
data.put("sfzh", "111111111111111111");

//这里是处理图片
//获取项目的部署路径(因为我的图片在服务器中)
		String realPath = request.getSession().getServletContext().getRealPath("/").replace(request.getContextPath().replaceAll("/", ""), ""); 
		String img = null;
        InputStream in;
        byte[] picdata = null;
        try {
//读取图片
            in = new FileInputStream(realPath+"images/rl/image_123.jpg");
            picdata = new byte[in.available()];
            in.read(picdata);
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        BASE64Encoder encoder = new BASE64Encoder();
        img = encoder.encode(picdata);
		
		data.put("image", img);
		
        //参数解释(第一个参数是模板文件的名称,第二、三个拼成生成文件的名称(这样文件名就叫文档名称-文档1.doc),第四个是数据map)
		WordUtil.word("rqpz.ftl", "文档名称", "文档1", data);

6.另附WordUtil的源码

public class WordUtil {
	public static void word(String ftl,String tb,String ryname,Map<String, Object> map) throws TemplateException, IOException{
		HttpServletResponse response = ServletActionContext.getResponse(); 
		response.reset(); 
		Configuration configuration = new Configuration();
        configuration.setDefaultEncoding("utf-8");
        //获取模板所在的路径
        configuration.setDirectoryForTemplateLoading(new File("D:/template/"));
        //以utf-8的编码读取ftl文件
        Template t =  configuration.getTemplate(ftl,"utf-8");
        String fileName = URLEncoder.encode(tb+"-"+ryname,"UTF-8") + ".doc";
        //1.设置文件ContentType类型,这样设置,会自动判断下载文件类型
        response.setContentType("multipart/form-data");
        //2.设置文件头:最后一个参数是设置下载文件名
        response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
        Writer out1 = new BufferedWriter(new OutputStreamWriter(response.getOutputStream(), "utf-8"),10240);
        t.process(map, out1);
        out1.close();
	} 
	
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值