当前位置: 移动技术网 > IT编程>开发语言>Java > SpringBoot引用阿里easyexcel,Excel导出返回浏览器下载

SpringBoot引用阿里easyexcel,Excel导出返回浏览器下载

2020年07月29日  | 移动技术网IT编程  | 我要评论

现在大的小的系统,各家的产品都差不多,一般运营或者产品规划的时候都会要求做一些导入导出数据的功能,他说供我统计或汇报用。好吧,我们苦逼的程序员开始干活了。

我们需要快速又简单的导出数据,这里介绍用到阿里巴巴开发的easyexcel开源插件。

首先我们在springboot项目中,引入easyexcel的maven坐标,在pom.xml文件中配置如下:

<dependency>
	<groupId>com.alibaba</groupId>
	<artifactId>easyexcel</artifactId>
	<version>2.2.6</version>
</dependency>

实现导出的思路,分以下几步走:

1、和管理后台普通的查询列表一样,设计Api需要具备按条件查询的能力

2、按条件查询出满足条件的records,封装成List集合返回

3、使用easyexcel构建的工具类通过字节流读取,搭档输出流将数据写入Excel


下面从底层查询说起吧

1、mybatis的mapper查询数据

这个就是上面说到的按条件查询,我就不细说了,这个就是正常的查询

2、service层返回查询的数据

这个就是说嘛说到的得到数据,封装为list,返回上一层,此处可处理自己的业务逻辑

3、control层调用服务层会得到数据list

a、得到list后,使用easyexcel方法读取字节流,写入到excel文件,输出到浏览器,参考下面的代码

List<InfoExcelVo> list = InfoService.getInfoExcelList(input);

if (CollectionUtils.isEmpty(list)) {
	return;
}

String fileName = System.currentTimeMillis() + "";
ExcelWriter excelWriter = null;
try {
	ServletOutputStream out = getOutputStream(fileName, response);
	excelWriter = EasyExcel.write(out, InfoExcelVo.class).build();

	WriteSheet writeSheet = EasyExcel.writerSheet("模板").build();
	excelWriter.write(list, writeSheet);
	out.flush();
} finally {
	// 千万别忘记finish 会帮忙关闭流
	if (excelWriter != null) {
		excelWriter.finish();
	}
}

return;

b、OutputStream字节流封装方法如下

/**
 * 导出文件时为Writer生成OutputStream
 *
 * @param fileName
 * @param response
 * @return
 */
private static ServletOutputStream getOutputStream(String fileName, HttpServletResponse response) throws Exception {
	try {
		fileName = URLEncoder.encode(fileName, "UTF-8");
		response.setContentType("application/vnd.ms-excel");
		response.setCharacterEncoding("utf8");
		response.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".xlsx");
		response.setHeader("Pragma", "public");
		response.setHeader("Cache-Control", "no-store");
		response.addHeader("Cache-Control", "max-age=0");
		return response.getOutputStream();
	} catch (IOException e) {
		throw new Exception("导出excel表格失败!", e);
	}
}

c、输入到excel时,InfoExcelVo对象就是你需要输入到excel的对象,下面是一个定义

@Data
@ApiModel(value = "InfoExcelVo对象", description = "导出excel")
public class InfoExcelVo implements Serializable {
 
	@ExcelProperty(value = "字段1", index = 0)
	private String field1;

	@ExcelProperty(value = "字段2", index = 1)
	private String field2;

	@ExcelProperty(value = "字段3", index = 2)
	private String field3;

}

以上就是使用easyexcel导出excel的思路和代码演示,希望能对大家的开发有所帮助。

来源:移动技术网,转载请保留文章出处

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网