1.引用easypoi最新pom
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-spring-boot-starter</artifactId>
<version>4.2.0</version>
</dependency>
2.对象定义
public class StudentEntity implements java.io.Serializable {
/**
* id
*/
private String id;
/**
* 学生姓名
*/
@Excel(name = "学生姓名", height = 20, width = 30, isImportField = "true_st")
private String name;
/**
* 学生性别
*/
@Excel(name = "学生性别", replace = { "男_1", "女_2" }, suffix = "生", isImportField = "true_st")
private int sex;
@Excel(name = "出生日期", databaseFormat = "yyyyMMddHHmmss", format = "yyyy-MM-dd", isImportField = "true_st", width = 20)
private Date birthday;
@Excel(name = "进校日期", databaseFormat = "yyyyMMddHHmmss", format = "yyyy-MM-dd")
private Date registrationDate;
}
3.生成Excel代码demo
public void getExcel(HttpServletResponse response) throws IOException {
StudentEntity studentEntity1 = new StudentEntity();
studentEntity1.setBirthday(new Date());
studentEntity1.setId("1");
studentEntity1.setName("hhh");
studentEntity1.setSex(1);
studentEntity1.setRegistrationDate(new Date());
StudentEntity studentEntity2 = new StudentEntity();
studentEntity2.setBirthday(new Date());
studentEntity2.setId("1");
studentEntity2.setName("hhh");
studentEntity2.setSex(2);
studentEntity2.setRegistrationDate(new Date());
StudentEntity studentEntity3 = new StudentEntity();
studentEntity3.setBirthday(new Date());
studentEntity3.setId("1");
studentEntity3.setName("hhh");
studentEntity3.setSex(2);
studentEntity3.setRegistrationDate(new Date());
List<StudentEntity> list = new ArrayList();
list.add(studentEntity1);
list.add(studentEntity2);
list.add(studentEntity3);
Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("计算机一班学生","学生"),
StudentEntity.class, list);
downLoadExcel("coming", response, workbook);
}
private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) throws IOException {
try {
response.setCharacterEncoding("UTF-8");
response.setHeader("content-Type", "application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName + "." + ExcelTypeEnum.XLS.getValue(), "UTF-8"));
workbook.write(response.getOutputStream());
} catch (Exception e) {
throw new IOException(e.getMessage());
}
}
/**
* Excel 类型枚举
*/
enum ExcelTypeEnum {
XLS("xls"), XLSX("xlsx");
private String value;
ExcelTypeEnum(String value) {
this.value = value;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}