将内容按照模板导出成xml、csv等,使用框架FreeMarker。
使用方法
-
导入jar包:freemarker-2.3.19.jar
-
定义模板:Alarm.ftl
<?xml version="1.0" encoding="UTF-8"?>
<triggers>
<#list alarmList as alarm>
<trigger>
<id>id: ${alarm.id!}</id>
<name>name: ${alarm.alarmname!}</name>
</trigger>
</#list>
</triggers>
#list
表示在写入数据时会遍历alarmList取出每个元素。${alarm.id!}
表示在写入数据时会从alarm元素中取出id填入此处,!
允许此处数据为空。
- 定义AlarmVO类
public class AlarmVO implements Serializable {
private String id;
private String alarmname;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getAlarmname() {
return alarmname;
}
public void setAlarmname(String alarmname) {
this.alarmname = alarmname;
}
}
- 写一个工具类实现导出功能
public class TemplateParseUtil {
/**
* 根据模板文件生成导出文件
*
* @param templateDir 模板文件目录
* @param templateName 模板文件名
* @param data 数据
* @throws IOException
* @throws TemplateException
* @throws URISyntaxException
*/
public static File parse(String templateDir, String templateName, Map<String, Object> data)
throws IOException, TemplateException, URISyntaxException {
// 配置
Configuration cfg = new Configuration(Configuration.VERSION_2_3_22);
// 设置默认编码格式为UTF-8
cfg.setDefaultEncoding("UTF-8");
// 设置模板文件位置
ClassLoader classLoader = TemplateParseUtil.class.getClassLoader();
URI realTemplateDir = classLoader.getResource(templateDir).toURI();
cfg.setDirectoryForTemplateLoading(new File(realTemplateDir));
// 加载模板
Template template = cfg.getTemplate(templateName, "UTF-8");
// 创建目录
File dir = new File("export_file/");
if (!dir.exists()) {
dir.mkdirs();
}
// 在 export_file/ 路径下生成临时文件
File downloadFile = File.createTempFile("export_template", ".xml", dir);
// 往临时文件中写入内容
OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(downloadFile), "UTF-8");
template.process(data, writer);
writer.flush();
writer.close();
return downloadFile;
}
}
- 测试
public class Test {
public File doExport() {
File result = null;
// 数据
Map<String, Object> data = new HashMap<>();
List<AlarmVO> list = new arrayList<>();
data.put("alarmList", list);
String templateDir = "com/template";
String templateName = "Alarm.ftl";
try {
result = TemplateParseUtil.parse(templateDir, templateName, data);
} catch (Exception e) {
LOGGER.error("export file error: " + e);
}
return result;
}
}