技术说明:
springboot:2.1.4.RELEASE
jQuery
Ajax
mysql:8.0.32
作业背景
我现在有个实体类,数据库里面有1000行数据,我需要实现全部自动导出到Excel表格中,接下来就是实现这个功能的额,
pom.xml
<dependency><groupId>com.alibaba</groupId><artifactId>easyexcel</artifactId><version>4.0.2</version></dependency>
如下实体类,每个字段上面加入对应的注解,如下代码:@ExcelProperty(value = "编号",index = 0),value的值,就是导出Excel表格每列表头的值。index的值,就是你Excel表头的位置。第一个就是0开始。如果某个Excel表头不需要导入,使用@ExcelIgnore忽略
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class StaffDo{/***编号*/@ExcelProperty(value = "编号",index = 0)private Integer id;/***姓名*/@ExcelProperty(value = "姓名",index = 1)private String name;/***是否在职*/@ExcelProperty(value = "是否在职",index = 2)private Integer state;/*** 性别*/@ExcelProperty(value = "性别",index = 3)private String sex;/***电话*/@ExcelProperty(value = "联系电话",index = 4)private String phoneNumber;/*** 身份证*/@ExcelProperty(value = "身份证号",index = 5)private String idCard;/*** 居住地址*/@ExcelProperty(value = "居住地址",index = 6)private String address;/***入职时间*/@ExcelProperty(value = "入职时间",index = 7)@JsonFormat(timezone = "GMT+8",pattern = "yyyy-MM-dd")private Date entryTime;/***离职时间*/@ExcelProperty(value = "离职时间",index = 8)@JsonFormat(timezone = "GMT+8",pattern = "yyyy-MM-dd")private Date leaveDate;/***户籍地址*/@ExcelProperty(value = "户籍地址",index = 9)private String domicileAddress;/***紧急联系人*/@ExcelProperty(value = "紧急联系人",index = 10)private String contacts;/***紧急联系人-关系*/@ExcelProperty(value = "联系人关系",index = 11)private String relationship;/***紧急联系人电话*/@ExcelProperty(value = "联系人电话",index = 12)private String contactPhone;/***其他,备注*/@ExcelProperty(value = "备注",index = 13)private String other;}
后端代码,前端只需要实现一个导出按钮,发送exportExcel请求即可
/*** 导出Excel*/@RequestMapping("/exportExcel")@ResponseBodypublic void exportExcel(HttpServletResponse response) throws IOException {//设置响应头,告诉浏览器以下载方式打开,并设置下载文件名response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");response.setCharacterEncoding("UTF-8");String filename = URLEncoder.encode("员工信息表", "UTF-8").replaceAll("\\+", "%20");response.setHeader("Content-Disposition", "attachment; filename*=utf-8''" + filename + System.currentTimeMillis() + ".xlsx");//写入ExcelEasyExcel.write(response.getOutputStream(),StaffDo.class)//StaffDo这里对应你的实体类.sheet("sheet1")//Excel表名字sheet1,你可以改你想要的名字.doWrite(staffService.selectAllStaff());//这里staffService.selectAllStaff(),是我后端查询所有数据,你跟据你自己的代码更改}