java通过freemarker导出word文档(doc)

  1. 准备好模板,并调整好模板中的格式

  2. 将word文档另存为Word 2003 XML格式

  3. 更改模板后缀xml为ftl

  4. 使用freemarker标签替换数据

  5. 获取模板代码

    private static Configuration configuration = null; 
    private static Map<String, Template> allTemplates = null;
    static { 
          configuration = new Configuration(); 
          configuration.setDefaultEncoding("utf-8"); 
          configuration.setClassForTemplateLoading(WordGenerator.class, "/download"); 
          allTemplates = new HashMap<String, Template>();
          try { 
              // 模板 
              Template recordTemplates = configuration.getTemplate( "test.ftl", "UTF-8"); 
              allTemplates.put("template", recordTemplates); 
          } catch (IOException e) { 
              e.printStackTrace(); 
              throw new RuntimeException(e); 
          } 
    }

     

  6. 生成word代码

    public static File createDoc(Map<?, ?> dataMap, String type, String tempFileDir) { 
        // 临时文件名称 
        String name = "temp" + (int) (Math.random() * 100000) + ".doc"; 
        File fileMkDir = new File(tempFileDir); 
        // 如果文件夹不存在则创建 
        if (!fileMkDir.exists() && !fileMkDir.isDirectory()) { 
            fileMkDir.mkdir(); 
        } 
        File file = new File(tempFileDir, name); 
        // 获取模板 
        Template template = allTemplates.get(type); 
        try { 
             Writer out = null; 
             FileOutputStream fos = null; 
             fos = new FileOutputStream(file); 
             OutputStreamWriter writer = new OutputStreamWriter(fos, "UTF-8"); 
             out = new BufferedWriter(writer); 
             template.process(dataMap, out); 
             out.flush(); 
             out.close(); 
        } catch (Exception ex) { 
             ex.printStackTrace(); 
             throw new RuntimeException(ex); 
        } 
        return file; 
    }

     

注: 1.若导出内容包含图片,需将图片转为base64编码

public static String getBase64ImgStrLocal(String imgFile) {
		// 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
		if (imgFile == null || imgFile == "") {
			return "";
		}
		File tempFile = new File(imgFile);
		if (!tempFile.exists() || !tempFile.isFile()) {
			return "";
		}

		InputStream in = null;
		byte[] data = null;
		// 读取图片字节数组
		try {
			in = new FileInputStream(tempFile.getAbsolutePath());
			data = new byte[in.available()];
			in.read(data);
			in.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		BASE64Encoder encoder = new BASE64Encoder();
		// String returnData = new String(Base64.encodeBase64(data));
		String returnData = encoder.encode(data);
		return returnData == null ? "" : returnData;
	}

        2.导出的word中包含特殊字符需进行替换:

        
        导出字段为null需替换成"",使用freemarker标签:${content!''}或${((content)!'')?html}(可替换特殊字符)

7.设置以浏览器的方式进行下载:

@RequestMapping("/export") 
@ResponseBody 
public void export(HttpServletRequest request,HttpServletResponse response) { 
     File file = null; 
     InputStream fin = null; 
     ServletOutputStream out = null; 
     try { 
         request.setCharacterEncoding("utf-8"); 
         //获取数据**** 
         Map<String,Object> map = ************** /
         /获取数据***** 
         file = WordGenerator.createDoc(map, "template", tmpStore); 
         fin = new FileInputStream(file); 
         String filename = "导出的word文件名"; 
         response.setCharacterEncoding("utf-8"); 
         response.setContentType("application/msword"); 
         // 设置浏览器以下载的方式处理该文件 
         filename = new String(filename.getBytes("gb2312"), "ISO8859-1"); 
         response.addHeader("Content-Disposition", "attachment;filename=" + """ + 
               filename + ".doc"); 
         out = response.getOutputStream(); 
         byte[] buffer = new byte[512]; 
         // 缓冲区 
         int bytesToRead = -1; 
         // 通过循环将读入的Word文件的内容输出到浏览器中 
         while ((bytesToRead = fin.read(buffer)) != -1) { 
                out.write(buffer, 0, bytesToRead); 
         } 
      } finally { 
         if (fin != null) { 
              fin.close(); 
         } if (out != null) { 
              out.close(); 
         } if (file != null) { 
               file.delete(); // 删除临时文件 
         } 
   }

 

转载于:https://my.oschina.net/keke412/blog/2963877

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值