模板引擎-freemarker

  Freemarker 是一款模板引擎,是一种基于模版生成静态文件的通用 工具,它是为java程序员提供的一个开发包。

可通过将Word或者Excel模板另存为xml格式,在其中修改要替换的内容。

基本语法

基本内容输出: 

${***}

List循环输出:

<#list namelist as item>
  ${item.name}
</#list>

item_index:当前变量的索引值
item_has_next:是否存在下一个对象
使用<#break>指令跳出迭代

List的总数获取:

${namelist?size}

Map循环输出:

<#list empMap?keys as key>
        ${empMap[key]}
</#list>

 设定变量:

<#assign age=23>

判断:

表达式中支持的比较运算符有如下几个:  

=或者==:判断两个值是否相等.  

 !=:判断两个值是否不等.  

>或者gt:判断左边值是否大于右边值  

 >=或者gte:判断左边值是否大于等于右边值  

<或者lt:判断左边值是否小于右边值  

<=或者lte:判断左边值是否小于等于右边值

<#if (name == 'zhangsan') >
    zhangsan 
<#elseif (name == 'lisi')>
  lisi
<#else>
  wangwu
</#if>

默认值:

${empMap['name']?default("wangwu")} 
${empInfo.empName?default('')}

null值判断和处理:

${empMap[key]!("null")}
?default('')
<#if empMap[key]??></#if>
${empMap['name']?if_exists

日期处理:

?string("yyyy/M/d")

<#if items.birthday??>${items.birthday?string("yyyy/M/d")}</#if>

数字格式化:

${strnum?string(",##0.0#")}

${strnum?string("#0.0#")}

 excel使用

在excel中设置好模板,模板内容最好先用要替代的字段名称代替,方便替换。将excel另存为xml格式文件。

打开xml文件找到<Row>将替换内容用${***}代替,同时循环行添加<# list>。

因有时excel设置有最大行数限制,因此需要修改Worksheet的属性ss:ExpandedRowCount,ss:ExpandedColumnCount设置为一个合理的范围。

否则最后生成excel后会有打不开报错的情况。

/**
 * @Description: 导出文件,使用FreeMarker
 * @author DennyZhao
 * @date 2017年12月20日
 * @version 1.0
 */
public abstract class ExportController {
    
    public static Configuration config = null;
    static {
        String templatePath = File2Utils.getResourcePath() + "/ftl";
        try {
            config = new Configuration(Configuration.VERSION_2_3_27);
            config.setDefaultEncoding("UTF-8");
            config.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
            config.setDateFormat(Date2Utils.DATE_FORMAT_DEFAULT);
            config.setDirectoryForTemplateLoading(new File(templatePath));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 获取数据
     * @return
     */
    protected abstract Map<String, Object> getData(SearchCondition condition);
    
    public void createTemplateStream(HttpServletResponse resp, String fileName, SearchCondition condition) {
        Template template = null;
        try {
            template = config.getTemplate(fileName);
            Writer osw = new OutputStreamWriter(resp.getOutputStream(), CommonConstants.ENCODE_CHARSET_DEFAULT);
            template.process(getData(condition), osw);
            osw.flush();
            osw.close();
        } catch (TemplateNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (MalformedTemplateNameException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (TemplateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 文件模板下载
     * @param outputStream
     * @throws IOException 
     */
    public void createFileModelStream(HttpServletResponse resp,String fileName) throws IOException {
        OutputStream os = resp.getOutputStream();
        String modelFilePath = File2Utils.getResourcePath() + "/fileModel";
        File file = new File(modelFilePath, fileName);
        InputStream is = new FileInputStream(file);
        resp.setContentLengthLong(is.available());
        byte[] b = new byte[1024];
        int count = 0;
        while((count = is.read(b, 0, 1024)) > 0) {
            os.write(b, 0, count);
        }
        is.close();
        os.flush();
        os.close();
    }
    
    
}
View Code

参考文章:

Freemarker实例教程(http://blog.csdn.net/chenghui0317/article/details/7832474)

另类:JAVA用freemarker生成复杂Excel(http://blog.csdn.net/zhanwentao2/article/details/7298341)

原文地址:https://www.cnblogs.com/DennyZhao/p/8075244.html