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

news/2024/7/5 1:01:42 标签: java, python

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

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

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

  3. 更改模板后缀xml为ftl

  4. 使用freemarker标签替换数据

  5. 获取模板代码

    java">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代码

    java">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编码

java">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.设置以浏览器的方式进行下载:

java">@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


http://www.niftyadmin.cn/n/834752.html

相关文章

客户故事:4家银行如何打造新一代移动金融中心

2019独角兽企业重金招聘Python工程师标准>>> 摘要&#xff1a; 数字金融时代&#xff01; ​小蚂蚁说&#xff1a; 我国"十三五"信息化规划明确提出&#xff0c;全球信息化将进入全面渗透、跨界融合、加速创新、引领发展的新阶段。未来&#xff0c;以云计…

Pointers in Python: What's the Point?

链接: https://realpython.com/pointers-in-python/ 转载于:https://www.cnblogs.com/fydeblog/p/10963018.html

浅谈BeanUtils的拷贝,深度克隆

2019独角兽企业重金招聘Python工程师标准>>> 1、BeanUtil本地简单测试 在项目中由于需要对某些对象进行深度拷贝然后进行持久化操作&#xff0c;想到了apache和spring都提供了BeanUtils的深度拷贝工具包&#xff0c;自己写了几个Demo做测试&#xff0c;定义了两个类…

python中的字典生成式

#需求1:假设有20个学生&#xff0c;学生的分数在60&#xff5e;100之间&#xff0c;筛选出成绩在90分以上的学生 import random stuInfo {}for i in range(20):name westos str(i)score random.randint(60, 100)stuInfo[name] scoreprint(stuInfo) highscore {}for name,…

DOM 获取、DOM动态创建节点

一、Dom获取 1、全称&#xff1a;Document Object Model  文档对象模型 2、我们常用的节点类型 元素&#xff08;标签&#xff09;节点、文本节点、属性节点&#xff08;也就是标签里的属性&#xff09;、 3、document有个属性叫nodeType返回的是数字 1&#xff1a;代…

超8千Star,火遍Github的Python反直觉案例集!

大数据文摘授权转载 作者&#xff1a;Satwik Kansal 译者&#xff1a;暮晨 Python&#xff0c;是一个设计优美的解释型高级语言&#xff0c;它提供了很多能让程序员感到舒适的功能特性。 但有的时候&#xff0c;Python的一些输出结果对于初学者来说似乎并不是那么一目了然。 这…

Weex Eros快速入门

概述 随着Weex跨平台技术的持续火热&#xff0c;一时间涌现出了一大批基于Weex的开源解决方案&#xff0c;Weex Eros就是这么一个面向前端Vue的开源APP解决方案。目前&#xff0c;如果直接使用Weex框架开发应用会存在很多痛点&#xff0c;诸如初始化启动的环境问题、项目工程化…

x64 assembler fun-facts(转载)

原文地址 While implementing the x64 built-in assembler for Delphi 64bit, I got to “know” the AMD64/EM64T architecture a lot more. The good thing about the x64 architecture is that it really builds on the existing instruction format and design. However, …