freemarker导出word

freemarker导出word,从前台方法都后台接口全部代码,可直接使用

vue导出事件

    // 导出
    async exportWord() {
      this.formdata = JSON.parse(JSON.stringify(this.form))
      const response = await exportAllDetail(this.formdata);
      const data = response.data;
      const blob = new Blob([data], {
          type: "application/msword",
      });
      const link = document.createElement("a"); //创建a标签
      document.body.appendChild(link); //将a追加到页面上
      let objectUrl = URL.createObjectURL(blob);
      link.href = objectUrl;
      let wordName = '测试导出'
      link.download = `${wordName}详情`; // 自定义文件名
      link.click(); // 下载文件
      document.body.removeChild(link); //将a从页面上删除
      URL.revokeObjectURL(objectUrl); // 释放内存
    },
/**
 * 导出word
 * @param {*} data 
 * @returns 
 */
export function exportAllDetail(data) {
  return request({
    url: '/exportAllDetail',
    method: 'post',
    data: data,
    responseType: 'arraybuffer'
  })
}

java接口

	public void exportAllDetail(
			@RequestBody(required = true) FoodsafetyManageinfoMonthMaintainPo detailPo, HttpServletResponse response) {
		Map<String, Object> hashMap = new HashMap<>();
		hashMap.put("year", detailPo.getYear());
		...
		
		String path = this.getClass().getResource("/").getPath() + "/template/"; // linux环境用
		//String path = "F:\\tmp\\template\\";  // 本地环境用
		String targetFileName = "详情.docx";
		String templateFileName = "detailData.ftl";
		commonExportWord(hashMap, path, templateFileName, targetFileName, response);
	}
    
    /**
     * 导出word通用方法
     * @param hashMap 模板数据项集合
     * @param path 模板所在文件夹,分隔符结尾
     * @param templateFileName 模板文件名,带后缀
     * @param targetFileName 导出的文件名,带后缀
     * @param response 响应流,到前端供下载
     */
    private void commonExportWord(Map<String, Object> hashMap, String path,String templateFileName, String targetFileName,
    		HttpServletResponse response) {
    	Configuration configuration = new Configuration(new Version("2.3.28"));
		configuration.setDefaultEncoding("utf-8");
    	PrintWriter writer = null;
		try {
			configuration.setDirectoryForTemplateLoading(new File(path));
			response.setContentType("application/msword");
			response.setHeader("Content-Disposition", "attachment;filename=" + new String(targetFileName.getBytes("utf-8"), "ISO8859-1"));
			response.setCharacterEncoding("utf-8");
			writer = response.getWriter();
			Template template = configuration.getTemplate(templateFileName, "utf-8");
			template.process(hashMap,writer);
			writer.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			writer.close();
		}
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值