ftl模板导出excel_freeMarker生成word,excel文档

以前导出文档一直使用poi技术,这个项目使用freemarker技术,然后看了一下,发现比poi简单多了。于是发表一下。

FreeMarker是一款模板引擎: 即一种基于模板和要改变的数据,并用来生成输出文本(HTML网页、电子邮件、配置文件、源代码等)的通用工具。它不是面向最终用户的,而是一个Java类库,是一款程序员可以嵌入他们所开发产品的组件。

首先,把你要导出的word文档另存为xml格式,然后使用记事本将它打开,将动态生成的代码用el表达式(jstl标签)替换。

示例如下:

word文档

姓名:aaa

性别:bbb

另存为xml后打开,修改如下姓名:${name}

性别:${sex}

用${name}和${sex}代替aaa和bbb。然后在后台编写java代码。package com.freemarkes.word;

import java.io.IOException;

import java.io.Writer;

import java.util.Map;

import org.apache.commons.logging.Log;

import org.apache.commons.logging.LogFactory;

import freemarker.template.Configuration;

import freemarker.template.Template;

import freemarker.template.TemplateException;

public class WordHandler {

private Configuration configuration = null;

Log logger = LogFactory.getLog(WordHandler.class);

public WordHandler() {

configuration = new Configuration();

configuration.setDefaultEncoding("UTF-8");

}

/*

* configuration跟文件路径有关系,是相对的。

*/

private Template getTemplate(String templatePath, String templateName) throws IOException {

configuration.setClassForTemplateLoading(this.getClass(), templatePath);

/***

* public void setClassForTemplateLoading(Class clazz, String pathPrefix);

* public void setDirectoryForTemplateLoading(File dir) throws IOException;

* public void setServletContextForTemplateLoading(Object servletContext, String path);

*看名字也就知道了,分别基于类路径、文件系统以及Servlet Context。

***/

Template t = null;

t = configuration.getTemplate(templateName);

t.setEncoding("UTF-8");

return t;

}

public void write(String templatePath, String templateName, Map dataMap, Writer out) throwsException {

try {

Template t = getTemplate(templatePath, templateName);

t.process(dataMap, out);

} catch (Exception e) {

logger.error(e);

} finally{

out.close();

}

}

public static void main(String[] args) throws Exception {

Map map=getMap();

WordHandler handler = new WordHandler();

Writer out = new OutputStreamWriter(new FileOutputStream("D:\\chaoslee.doc"), "UTF-8");

handler.write("", "chaoslee.xml", map, out);

}

public static Map getMap(){

Map map = new HashMap();

map.put("name", "chaoslee");

map.put("sex", "男");

return map;

}

}

运行main方法就可以导出word文档了。代码见附件

我的xml文档是复制的片段,所以可能不能使用,如果有使用的人,还是自己另存为一下。

这个博客不能复制图片让我很是为难啊,还是 我不会复制。复制的都是空白的。

Excel方法也差不多。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值