首先,在SpringBoot中使用EasyPoi少不了包的集成,在这里提供了EasyPoi的包:
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-spring-boot-starter</artifactId>
<version>4.0.0</version>
</dependency>
对于浏览器中的表的数据,需要在我们的实体类中将数据的字段与属性一一对应进行封装,使用@Excel注解进行注解导出,每列数据的列名使用@Excel(name属性),代码如下所示:
public class StudentClient implements Serializable {
@Excel(name = "手机号")
private String mobile;
@Excel(name = "姓名")
private String name;
对于一些字段,查找出的数据与导出的数据内容不一致,属于一种对应关系,如:1对应男,2对应女,想要进行对应关系的转换,可使用@Excel的replace属性;如下所示:
@Excel(name = "学生性别", replace = { "男_1", "女_2" })
private int sex;
具体其它一些属性暂不细说,有需要的小伙伴可查看开发文档:
2.4 注解变种-代码注解导出 - Powered by MinDoc
一:Excel文件本地导出
在数据所对应的实体类封装好之后,就可以进行导出功能的代码编写了。做一个简单的本地导出数据;
List<StudentClient > list = new ArrayList<StudentClient>();
for (int i = 0; i < 5; i++) {
StudentClient client = new StudentClient();
client.setClientName("小廖" + i);
client.setClientPhone("438" + i);
client.setRemark("测试" + i);
list.add(client);
}
Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("测试", "测试"), StudentClient.class, list);
File savefile = new File("D:/excel/");
if (!savefile.exists()) {
savefile.mkdirs();
}
FileOutputStream fos = new FileOutputStream("D:/excel/ExcelExport.xlsx");
workbook.write(fos);
fos.close();
感谢爱心观众小廖的参加,导出数据效果图如下:
二:浏览器导出Excel文件
在平常的开发中,多用于浏览器数据导出,上面算一个小小的入门;在浏览器中数据导出文件;获取响应对象进行编码格式等一系列设置;然后使用流进行数据输出就OK了。简简单单的操作,快速上手。
Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(title, sheetName), Class, Object);
HttpServletResponse response = WebUtils.response();// 获取响应对象
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");// 设置编码格式
String fileName = URLEncoder.encode(title, "utf-8");// 设置文件名和格式
response.setHeader("Content-dispodition", "attachment;filename="+fileName);
ServletOutputStream outputStream = response.getOutputStream();// 获取输出流
workbook.write(outputStream);// 输出
outputStream.close();// 关流
二:模板导出
使用方法大同小异,还是需要封装一个导出的对象实体类
在业务的处理当中比较于注解导出有所不同的地方是:
outBoundOrderClient.setOutBoundOrderFreightListClients(outBoundList);
Map<String, Object> map = new HashMap<>();
map.put("outBoundOrderClient", outBoundOrderClient);
//1.获取excel模板
ClassPathResource classPathResource = new ClassPathResource("template/outboundDeliveryOrderTemplate.xlsx");
TemplateExportParams params = new TemplateExportParams(classPathResource.getPath());
Workbook workbook = ExcelExportUtil.exportExcel(params, map);
HttpServletResponse response = WebUtils.response();
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
ServletOutputStream outputStream = null;
这里就是比较重要的一段,最后的封装是使用map进行封装,后面的模板中会使用到表达式,跟此处的key-value有关系,模板别忘了放置到resources中
最后说一说他的表达式:
表达式的开头:
直接贴图,使用比较简单,API中也有很清楚的说明;
文章到这里就结束了!!!