java 根据模板,导出word并提供下载

  java+springmvc实现根据freemarker模板导出word模板。模板使用的后缀能够是:.xml,也能够是.ftl。html

步骤1,引入freemarker的jar包。java

步骤2,制做模板文件。(红框中的内容是为了替换使用)spring

 

另存为xml格式,mvc

 

 

找到xml文件,右键用editplus打开,找到红框的标记1,标记2进行修改。app

若是是表格的话,表头的第一行须要保留。dom

表格的主体部分须要保留一个,测试

这里eList是从后台赋值的一个集合,${e_index+1}是根据<#list eList as e>这个别名+_index获得,用法基本与el表达式用法相同。this

这样一个模板就完成了,将模板复制进项目中便可,后缀是什么不重要,重要的是咱们用freemarker解析编码

步骤4,java后台代码。spa

        @RequestMapping("/test/toWord")
	public ModelAndView toWord(HttpServletRequest request, HttpServletResponse response) throws IOException{
		
		File file = createDoc();
		
		response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("UTF-8");
        java.io.BufferedInputStream bis = null;
        java.io.BufferedOutputStream bos = null;

        try {
            long fileLength = file.length();
            response.setContentType("application/msword");
            response.setHeader("Content-disposition", "attachment; filename="
                    + URLEncoder.encode("测试的,统计-导出时间"+DateTimeUtils.getDateTime("yyyyMMddHHmmss")+".doc", "utf-8"));
            response.setHeader("Content-Length", String.valueOf(fileLength));
            bis = new BufferedInputStream(new FileInputStream(file));
            bos = new BufferedOutputStream(response.getOutputStream());
            byte[] buff = new byte[2048];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bis != null)
                bis.close();
            if (bos != null)
                bos.close();
        }
		
		return null;
	}
	
	private File createDoc(){
		// 建立数据
		Map<String,Object> dataMap = new HashMap<String, Object>();
		
		dataMap.put("cwlx", "测试的");
                List<?> eList = new ArrayList<?>();// 这里是获取list列表的方法
		dataMap.put("czsj",DateTimeUtils.getDateTime("yyyyMMddHHmmss"));// 这里是获取当前时间的一种方式,能够根据本身程序自行修改
		dataMap.put("eList", eList);
		
		// 获取模板
		Configuration configuration = new Configuration();
		configuration.setDefaultEncoding("utf-8");
		configuration.setClassForTemplateLoading(this.getClass(), "/tpl");
		Template t = null;
		
		String name = "temp"+(int)(Math.random()*1000)+".doc";
		File file = new File(name);
		try {
			t = configuration.getTemplate("model.xml");
			t.setEncoding("UTF-8");
			
			Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(name),"UTF-8"));
			t.process(dataMap, out);
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (TemplateException e) {
			e.printStackTrace();
		}
		return file;
	}

  在前台页面是须要作的就是发送一个连接就能够了。

特别注意,

常常忽视的问题,编码的问题,这里须要统一编码。

若是出现了word文件不能打开的状况,建议看一下后台文件是否报错。若是后台没有报错的话,建议用editplus打开word的文档,查看文档中是否有乱码的状况。

笔者第一次使用的时候,常常出现word文件不能打开的问题,因而我在editplus中打开,发现部分汉字是乱码的,加了上图红框中的默认编码的设置以后就能够了。

 

以上代码是本人亲测过的,能够放心使用。若有不明白的地方,欢迎交流。若有不正确的地方或累赘的地方也能够互相交流。

相关文章
相关标签/搜索