1、背景

文件操作中导入导出功能在项目中十分常见,这里我们要聊的是导出excel这一功能。老话题常谈常新,小编给大家介绍使用freemark模板的方式导出excel。

2、实现

Demo中采用springBoot+mybatis整合项目,其他项目配置类似。

2.1 添加jar

pom.xml中配置freemark所需的jar包,如下所示:

org.springframework.boot
spring-boot-starter-freemarker

2.2 准备模板

修改excel模板(即后续导出的excel模板,包括列名和样式等内容)的扩展名为.xml文件格式。打开文件,这里需要修改一处参数。

2.2.1 修改行数

将上述代码中的“ss:ExpandedRowCount”属性的值设置为${exports?size+15} ,其中,exports是后台准备数据的值,即下面代码中map中的key值。

如果您能预估到表格中数据的条数,可以直接设置一个较大的值。

2.2.2 填充数据

这里的用法和一般的模板引擎以及jsp的用法都很类似,只要清楚具体用法就可以了,这里取一小段做示例。

0)>
${(p.student.schoolNo)!'无'}
${(p.student.systemNo)!'无'}
${(p.student.name)!'无'}
男
女
#if>
#list>

Tips:

1) 做好判空处理,否则模板会直接报错

2)保持excel代码中原有数据值不变,比如上述的ss:StyleID等。另外,每个标签都要跟上结束标签,否则生成的excel会无法打开。

修改完毕后,将文件保存为.ftl格式的文件,即freemark模板文件格式。

2.3 后台实现

@RequestMapping("index")
public void index(HttpServletRequest request, int oaId,String startDate,HttpServletResponse response, Model model) {
//填充模板的数据Vo
Map map=getPermission(oaId,startDate);
File file = null;
InputStream inputStream = null;
ServletOutputStream out = null;
try{
request.setCharacterEncoding("UTF-8");
file = new ExcelUtil().createExcel(request,map, "myExcel","all.ftl");//调用创建excel帮助类,其中all.ftl为模板名称
inputStream = new FileInputStream(file);
response.setCharacterEncoding("utf-8");
response.setContentType("application/msexcel");
response.setHeader("content-disposition", "attachment;filename="+ URLEncoder.encode("name" + ".xls", "UTF-8"));
out = response.getOutputStream();
byte[] buffer = new byte[512]; // 缓冲区
int bytesToRead = -1;
// 通过循环将读入的Excel文件的内容输出到浏览器中
while ((bytesToRead = inputStream.read(buffer)) != -1) {
out.write(buffer, 0, bytesToRead);
}
out.flush();
if (inputStream != null) {
inputStream.close();
}
file.delete(); //导出到浏览器后,删除项目中的临时文件
}catch(Exception e){
}
}

Utils工具类:

public File createExcel(HttpServletRequest request, Map, ?> dataMap, String type, String valueName){
realPath=request.getServletContext().getRealPath("");
try {
configuration = new Configuration();
configuration.setDefaultEncoding("UTF-8");
configuration.setDirectoryForTemplateLoading(new File(realPath+""));
allTemplates = new HashMap();
allTemplates.put(type, configuration.getTemplate(valueName));
} catch (IOException ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
String name = "temp" + (int) (Math.random() * 100000) + ".xls";
File file = new File(name);
Template template = allTemplates.get(type);
try {
Writer w = new OutputStreamWriter(new FileOutputStream(file), "utf-8");
template.process(dataMap, w);
w.close();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
return file;
}

导出excel如下所示:

freemarker word 中增加动态表格 freemarker动态生成表格_导出excel

3、小结

使用模板生成excel适用于要展示的数据项较多,并且样式十分复杂的需求中。如果使用纯Java代码来编写这样复杂的excel,极易出错而且工作量很大。

学会变通,不同场景使用不同的方式来解决。当你发觉一直在做体力活的时候,就应该闻到了坏代码的味道……