博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
模板引擎-freemarker
阅读量:7291 次
发布时间:2019-06-30

本文共 3899 字,大约阅读时间需要 12 分钟。

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

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

基本语法

基本内容输出: 

${***}

List循环输出:

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

 

item_index:当前变量的索引值

item_has_next:是否存在下一个对象
使用<#break>指令跳出迭代

List的总数获取:

${namelist?size}

 

Map循环输出:

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

 设定变量:

<#assign age=23>

 

判断:

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

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

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

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

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

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

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

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

默认值:

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

null值判断和处理:

${empMap[key]!("null")} ?default('')<#if empMap[key]??>
${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
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

你可能感兴趣的文章
Netty序列化-Protobuf
查看>>
unity3d的资源管理和热更新方案
查看>>
RHEL7服务命令
查看>>
RMAN 参数详解
查看>>
C++系统学习之C库assert
查看>>
《Kotlin 极简教程 》第16章 使用 Kotlin Native
查看>>
KIBANA
查看>>
apl脚本入门-脚本中定义方法(函数), 类
查看>>
linux 网络管理
查看>>
新型SNS人魔网
查看>>
golang sync.WaitGroup解决goroutine同步
查看>>
JSONObject、JSONArray
查看>>
Nginx+Keepalived实现站点高可用
查看>>
asc ii 表
查看>>
ERP与ISO--ERP顾问的困惑之解
查看>>
我的友情链接
查看>>
Linux 虚拟内存和物理内存的理解
查看>>
python windows 安装paramiko报错
查看>>
玩转木浪云数据管理免费版使用篇之创建虚拟机一致性组
查看>>
新春特惠,全场7折
查看>>