Beetl模版引擎
0.简介
本文只简单介绍使用hutool中的BeetlUtil结合FileWriter实现模版文件的数据渲染
前提:pom引入hutool工具类
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>4.5.10</version>
</dependency>
1.编写模版文件
示例:
1.1 模版文件
文件路径:E:\model\easyModel.txt
#日期:${billDate}
#-----------------------------------------成绩列表----------------------------------------
姓名,年龄,成绩
<%
for(student in list){
%>
${student.name},'${student.id},${student.age},${student.score}
<% } %>
#-----------------------------------------成绩列表----------------------------------------
#导出时间:${time,dateFormat="yyyy-MM-dd HH:mm:ss"}
Excel显示数字时,如果数字大于12位,它会自动转化为科学计数法;如果数字大于15位,它不仅用于科学技术法表示,还会只保留高15位,其他位都变0。所以需要在id这里加一个符合【’】
1.2 实体类:
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Student implements Serializable {
private static final long serialVersionUID = -7271996307387758147L;
private String name;
private String id;
private Integer age;
private Integer score;
}
1.3 测试类
public static void main(String[] args) {
String billDate = "2020-04-29";
Map<String,Object> map = Maps.newHashMap();
map.put("time",new Date());
map.put("billDate",billDate);
Student student1 = Student.builder().name("小李").age(18).score(90)
.id("1005004171908261748056081").build();
Student student2 = Student.builder().name("小白").age(19).score(99)
.id("1005008601908261125575301").build();
List<Student> list = Lists.newArrayList();
list.add(student1);
list.add(student2);
map.put("list",list);
String content = BeetlUtil.render("E:\\model\\","easyModel.txt",map);
// 3.创建文件
FileWriter writer = new FileWriter("E:\\model\\output.csv", CharsetUtil.CHARSET_GBK);
writer.write(content);
}