java poi freemarker ftl 模板导出word

1、制作模板
用doc文件另存为Word 2003 XML文档(试过docx不行)
模板中内容替换 如
将时间替换为后台设置的字段${start1}~${end1}
将图片替换为后台传回的图片base64值 找到preserve标签 将原有的图片base64内容删除替换为“${img1}”
列表替换,找到列表中内容行 用<#list list5 as item></#list >将<w:tr>标签的内容包裹起来。表格值为序号:<w:t>${item_index+1}</w:t>;其他内容<w:t>${item.DWMC}</w:t>
修改好的模板保存为ftl文件
2、图片为页面显示的echarts图表,在页面中生成echarts图之后,

line_chart.getDataURL()

获取echarts图片的base64,作为参数传递给导出文档的接口。
3、页面调用


      $("#downloadReport").on('click',function(){
        params.img1=zcqktjImg;
        params.img2=zcflqktjImg;
        $.post('warehouse/report/exportGwcReportInfo',params,function(res){
          console.log(res);
          if(res.success) {
            var a = document.createElement('a');
            a.download = res.data.FILENAME_BAK;
            a.href = res.data.file;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
          } else {
            layer.msg("导出失败");
          }
        });
      });

4、java生成导出文档的参数

@RequestMapping(value = "/exportGwcReportInfo", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public ResponseWrapper exportGwcReportInfo(HttpSession session, HttpServletRequest request) {
        ResponseWrapper wrapper = new ResponseWrapper();
        wrapper.setCodeSuccess();
        PageData pd = this.getPageData();
        try {
            String yyyyddmm = DateUtil.date2StringDate(new Date(), "/yyyyMMdd/");
            String path = "assets/upload/gwc_report";
            String showPath = session.getServletContext().getRealPath(path) + yyyyddmm;
            String FILENAME= "gwc_report.doc";
            String FILENAME_BAK= "资产管理报告.doc";
            String templateFileName="gwc7.ftl";
            
            Map<String,Object> dataMap =getInfoData(pd);
            //图片
            dataMap.put("img1",FreeMarkerWordUtil.turn(pd.getString("img1")));
            dataMap.put("img2",FreeMarkerWordUtil.turn(pd.getString("img2")));
            //表格
            List<PageData> drdwList = gwcYearReportService.getDrDwTj(pd);
            dataMap.put("list5",drdwList);
            
            writeWordReport(showPath,FILENAME,templateFileName,dataMap,request);

            PageData pds = new PageData();
            pds.put("file", path+yyyyddmm+FILENAME);
            pds.put("FILENAME_BAK", FILENAME_BAK);
            wrapper.setData(pds);
            wrapper.setCodeSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            wrapper.setCodeFailed();
        }
        return wrapper;
    }
    public Map<String,Object> getInfoData(PageData pd){
        //添加模板数据
        Map<String,Object> dataMap = new HashMap<>();
        try {
            //查询报告信息
            //查询报告信息
            String start1=DateUtil.date2StringDate(DateUtil.fomatDate(pd.getString("START_TIME")), "yyyyMMdd");
            String end1=DateUtil.date2StringDate(DateUtil.fomatDate(pd.getString("END_TIME")), "yyyyMMdd");
            String start2=DateUtil.date2StringDate(DateUtil.fomatDate(pd.getString("START_TIME")), "yyyy年MM月dd日");
            String end2=DateUtil.date2StringDate(DateUtil.fomatDate(pd.getString("END_TIME")), "yyyy年MM月dd日");
            String timeStr="自"+start2+"起至"+end2+"止,";

            String now=DateUtil.date2StringDate(new Date(), "yyyy年MM月dd日");
            PageData tjInfo= gwcYearReportService.getGwcReportTjCALLABLE(pd);

            StringBuffer totalTj=new StringBuffer();
            totalTj.append("截止到"+now+",资产总量为"+tjInfo.getString("ALLNUMTOTAL")+"件,总价值"+DataUtil.je2wy(tjInfo.getBigDecimal("ALLJZTOTAL"))+"万元," );
            totalTj.append("其中:借出资产"+tjInfo.getString("JCNUMTOTAL")+"件,价值"+DataUtil.je2wy(tjInfo.getBigDecimal("JCJZTOTAL"))+"万元;" );
            totalTj.append("在库资产"+tjInfo.getString("ZKNUMTOTAL")+"件,价值"+DataUtil.je2wy(tjInfo.getBigDecimal("ZKJZTOTAL"))+"万元," );
            totalTj.append("借用单位数量为"+tjInfo.getString("JYDWNUMTOTAL")+"个,借用次数为"+tjInfo.getString("JYCSTOTAL")+"次。");
     
            dataMap.put("start1",start1);
            dataMap.put("end1",end1);
            dataMap.put("totalTj",totalTj.toString());
         
        }catch (Exception e){
            e.printStackTrace();
        }
        return dataMap;
    }
    public  Boolean writeWordReport(String wordFilePath, String wordFileName,
                                    String templateFileName, Map<String, Object> beanParams
            , HttpServletRequest request) {
        Writer out = null;
        try {
            String basePath = request.getServletContext().getRealPath("/");
            //1.创建配置类,这个configuration是freemarker提供的,不要导错包了
            Configuration configuration=new Configuration(Configuration.getVersion());
            //2.设置模板所在的目录,这里定义的就是刚刚test.ftl所存放的真实目录
            configuration.setDirectoryForTemplateLoading(new File(basePath+"/WEB-INF/ftl/"));  //注意这里是文件夹路径,不是文件路径
            //3.设置字符集
            configuration.setDefaultEncoding("utf-8");
            //4.加载模板
            Template template = configuration.getTemplate(templateFileName);

            //获取文件目录,如果不存在则创建
            String filePath = "";
            int index = wordFilePath.lastIndexOf(File.separator);
            if(index != wordFilePath.length()-1){
                filePath = wordFilePath+ File.separator;
            }else {
                filePath = wordFilePath;
            }
            File file1 = new File(filePath);
            if(!file1.exists()){
                file1.mkdirs();
            }

            //输出文件
            File file = new File(filePath+wordFileName);
            FileOutputStream fos = new FileOutputStream(file);
            out = new OutputStreamWriter(fos, "UTF-8");
            template.process(beanParams, out);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }finally{
            try {
                if(out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

报告需要查询的数据较多,数据库查询使用的存储过程,在mybatis中使用方法


	<select id="getGwcReportTjCALLABLE" parameterType="pd" resultType="pd" useCache="false" statementType="CALLABLE">
		{
			call GWC_REPORT2(
			#{START_TIME_STR,mode=IN,jdbcType=VARCHAR},
			#{END_TIME_STR,mode=IN,jdbcType=VARCHAR},
			#{ALLNUM,mode=OUT,jdbcType=INTEGER},
			#{ALLJZ,mode=OUT,jdbcType=DECIMAL},
			#{JCNUM,mode=OUT,jdbcType=INTEGER}
			...
			)
		}
	</select>
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值