使用xml、ftl模板生成word文档,下载到浏览器或指定位置

  1. 把模板word需要填充的地方写入内容并保存,然后另存为Word 2003 XML 文档(*.xml),把模板放到系统内。
  2. 根据填充的内容,找到对应的位置,使用替代掉填充内容,${tml}就是服务端传回此处内容的key,按照自己的习惯定义即可,的作用主要是防止服务端传参为空,或者没传会报错的问题,如果数据为List则使用list标签遍历,如下:
    
        
        
        
        <#list testMethodList as tml>
    	    
    	    
    	        
    	        
    	        
    	        
    	        
    	        
    	        
    	        
    	        
    	            
    	            
    	            
    	            
    	            
    	        
    	   
        
    

    特别注意试项:word文档是按列进行数据填充的,所以需要按照列的方式组织数据,但是又要兼顾每一行数据的位置对应

  3. 文件下载的方式:第一种是使用浏览器下载,代码如下,(参数说明:fileName为模板名称,带后缀;outName为文件输出时的名称,带后缀;writeData为模板中需要填充数据的map)(需要引入freemarker的jar):

  4. response.setContentType("application/msword");
    response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(outName, "UTF-8"));
    Writer writer = response.getWriter();
    Configuration cfg=new Configuration();
    String path =FtlHandler.class.getResource("/").getPath()+"ftl";
    TemplateLoader templateLoader = new FileTemplateLoader(new File(path));
    cfg.setTemplateLoader(templateLoader);
    cfg.setDefaultEncoding("UTF-8");//设置模板读取的编码方式,用于处理乱码
    Template template = cfg.getTemplate(fileName,"UTF-8");//模板文件,支持xml,ftl 也支持html
    template.process(writeData, writer);//将模板写到文件中
    writer.flush();
    cfg.clearTemplateCache();
    writer.close();

    第二种是下载到指定的位置,(参数说明:newTemp.ftl为模板名称;datas为模板中需要填充数据的map):

    Configuration cfg = new Configuration(); // 通过Freemaker的Configuration读取相应的ftl
    TemplateLoader templateLoader = new FileTemplateLoader(new File(AutoDownloadReportService.class.getResource("/").getPath() + "ftl"));
    cfg.setTemplateLoader(templateLoader);
    cfg.setDefaultEncoding("UTF-8");// 设置模板读取的编码方式,用于处理乱码
    Template template = cfg.getTemplate("newTemp.ftl", "UTF-8");// 模板文件,支持xml,ftl 也支持html
    File file = new File(path + "\\" + "胶料报告" + gnumber + " " + batch + ".doc");
    if (!file.getParentFile().exists())
    { // 判断有没有父路径,就是判断文件整个路径是否存在
        file.getParentFile().mkdir(); // 不存在就全部创建
    }
    Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "utf-8"));
    template.process(datas, out);
    out.flush();
    out.close();

你可能感兴趣的:(个人成长,java,xml)