SpringBoot集成EasyPoi的基本使用(注解导出和模板导出)
发布日期:2022-02-27 02:37:54 浏览次数:42 分类:技术文章

本文共 2719 字,大约阅读时间需要 9 分钟。

首先,在SpringBoot中使用EasyPoi少不了包的集成,在这里提供了EasyPoi的包:

cn.afterturn
easypoi-spring-boot-starter
4.0.0

对于浏览器中的表的数据,需要在我们的实体类中将数据的字段与属性一一对应进行封装,使用@Excel注解进行注解导出,每列数据的列名使用@Excel(name属性),代码如下所示:

public class StudentClient implements Serializable {    @Excel(name = "手机号")    private String mobile;    @Excel(name = "姓名")    private String name;

对于一些字段,查找出的数据与导出的数据内容不一致,属于一种对应关系,如:1对应男,2对应女,想要进行对应关系的转换,可使用@Excelreplace属性;如下所示:

@Excel(name = "学生性别", replace = { "男_1", "女_2" })private int sex;

具体其它一些属性暂不细说,有需要的小伙伴可查看开发文档:

一:Excel文件本地导出

在数据所对应的实体类封装好之后,就可以进行导出功能的代码编写了。做一个简单的本地导出数据;

List
list = new ArrayList
();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
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中也有很清楚的说明;

文章到这里就结束了!!!

转载地址:https://blog.csdn.net/weixin_43398098/article/details/118387380 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:LocalDateTime的时间差计算
下一篇:String,StringBuilder,StringBuffer三者之间的区别

发表评论

最新留言

表示我来过!
[***.240.166.169]2024年03月31日 14时07分00秒