freemarker总结

freemarker的作用

现在的任务是实现一个下载word文档的功能,而word文档是预先排版好的,我需要做的就是把从数据库或者别的地方拿到的数据填充到对应的位置。使用freemarker实现出来的效果很好。

freemarker的使用

首先需要一个word文档,将来你需要下载的文档是什么样就写成什么样,把需要填充的地方先写上数据。把文档另存为2003xml格式,然后打开xml文件,找到刚才填充的数据,使用${name}替换掉刚才填充的数据(name需要自己命名,一会儿需要根据此命名填充数据)。freemarker的模板类型可以是xml或者是ftl,如果使用ftl类型,只需要把后缀名改成ftl就行了。我使用的是xml。
接下来是代码实现:
首先引入jar报:

<dependency>
	<groupId>org.freemarker</groupId>
	<artifactId>freemarker</artifactId>
	<version>2.3.23</version>
</dependency>

然后在工具类里面写创建文档的方法:

 private static Configuration configuration = null;
    private static HashMap<String, Template> allTemplates = null;
    static {
        configuration = new Configuration();
        configuration.setDefaultEncoding("utf-8");
        try {
            configuration.setDirectoryForTemplateLoading(new File("D:/"));//此处是xml文档所在的目录,使用的是绝对路径。也有另外两种设置路径的方法,不过我用的时候会找不到xml文件。
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static File createDoc(Map<?, ?> dataMap, String type,String select) {
        String sel = null;
        if(select.equals("bzsq")){
            sel="bzsq.xml";
        }
        else if(select.equals("sqwt")){
            sel="sqwt.xml";
        }else if(select.equals("image")){
            sel="image.xml";
        }
        allTemplates = new HashMap<String, Template>();
        try {
            allTemplates.put("resume", configuration.getTemplate(sel));
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }

        String name = "test" + (int) (Math.random() * 100000) + ".doc";
        File f = new File(name);
        Template t = allTemplates.get(type);
        try {
            Writer w = new OutputStreamWriter(new FileOutputStream(f), "utf-8");
            t.process(dataMap, w);
            w.close();
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new RuntimeException(ex);
        }
        return f;
    }

    public static File createDoc(Map<?, ?> dataMap, String type) {
            String sel = null;
            sel="test.xml";
        allTemplates = new HashMap<String, Template>();
        try {
            allTemplates.put("resume", configuration.getTemplate(sel));
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }

        String name = "temp" + (int) (Math.random() * 100000) + ".doc";
        File f = new File(name);
        Template t = allTemplates.get(type);
        try {
            Writer w = new OutputStreamWriter(new FileOutputStream(f), "utf-8");
            t.process(dataMap, w);
            w.close();
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new RuntimeException(ex);
        }
        return f;
    }

或者创建excle

  public static File createXls(Map<?, ?> dataMap, String type) {

        allTemplates = new HashMap<String, Template>();
        try {
            allTemplates.put("resume", configuration.getTemplate("text.xml"));  //加载excel模板
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        String name = "temp" + (int) (Math.random() * 100000) + ".xls";
        File f = new File(name);
        Template t = allTemplates.get(type);
        try {
            Writer w = new OutputStreamWriter(new FileOutputStream(f), "utf-8");
            t.process(dataMap, w);
            w.close();
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new RuntimeException(ex);
        }
        return f;
    }

下载方法

public void bzsqDown(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("name","gyl");
        map.put("postalcode", "231188");
        map.put("telephone","1889273893");
        
        File file = null;
        InputStream fin = null;
        ServletOutputStream out = null;
        try {
            // 调用createDoc方法生成Word文档
            file=DownUtil.createDoc(map,"resume");
            fin = new FileInputStream(file);
            resp.setCharacterEncoding("utf-8");
            resp.setContentType("application/msword");
            
            // 设置浏览器以下载的方式处理该文件
           resp.addHeader("Content-Disposition","attachment;filename=test.doc");
            out = resp.getOutputStream();
            byte[] buffer = new byte[1024]; // 缓冲区
            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(); // 删除临时文件
        }
    }

其流程简要如下:

public void test1() throws Exception{
  //创建配置对象
  Configuration configuration = new Configuration(Configuration.getVersion()); 
  //设置模板文件所在的路径 
  configuration.setDirectoryForTemplateLoading(new File("D:/"));
  //设置字符集 
  configuration.setDefaultEncoding("UTF-8");
  //创建模板对象 
  Template template = configuration.getTemplate("test.xml"); 
  //创建数据集
  Map<String,Object> map = new HashMap<String,Object>();      
  map.put("type", "student");
  //创建Writer对象 
  File f = new File("temp.doc");
  Writer out = new OutputStreamWriter(new FileOutputStream(f), "utf-8");
  //使用模板对象输出文件 
  template.process(dataModel, out); 
  //关闭流
  out.close();
 }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值