easyExcel導出
此篇僅記錄導出功能的實現!
1、導入maven依賴
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.1.6</version>
</dependency>
2、實體類
@Data
public class JobLevel {
//不需要的的字段使用 @ExcelIgnore
@ExcelIgnore
private Integer id;
@ExcelProperty({"職位名稱"})
private String name;
@ExcelProperty({"職位等級"})
private String titleLevel;
//@DateTimeFormat("yyyy-MM-dd") 時間格式轉換
@ExcelProperty({"創建時間"})
@DateTimeFormat("yyyy-MM-dd")
@JsonFormat(pattern = "yyyy-MM-dd",timezone = "Asia/Shanghai")
private Date createDate;
@ExcelProperty(value={"是否啟用"}, converter = CustomBooleanConverter.class)
private Boolean enabled;
3、和表格模板相對應
@ExcelProperty({"職位名稱"})
private String name;
4、Boolean 類型轉換器
package com.carpxt.myhr.controller.config;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
/**
* @Author: tt
* @Date: 2020/12/17 20:38
* @Description: Boolen類型數據轉換器 實現Converter接口
* @Version: 1.0
*/
public class CustomBooleanConverter implements Converter<Boolean> {
@Override
public Class supportJavaTypeKey() {
return null;
}
@Override
public CellDataTypeEnum supportExcelTypeKey() {
return null;
}
@Override
public Boolean convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
return cellData.getBooleanValue();
}
@Override
public CellData convertToExcelData(Boolean value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
return new CellData(value?"是":"否");
}
}
5、導出代碼:
public void downloadJob(HttpServletResponse response) throws IOException {
List<JobLevel> jobLevelList = jobLevelMapper.getJobLevelList();
ClassPathResource classPathResource = new ClassPathResource("templates/exportStaTemplate.xlsx");
InputStream inputStream = classPathResource.getInputStream();
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
// 這里URLEncoder.encode可以防止中文亂碼 當然和easyExcel沒有關系
String fileName = URLEncoder.encode("測試", "UTF-8").replaceAll("\\+", "%20");
response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
// 如果不用模板的方式導出的話,是doWrite
EasyExcel.write(response.getOutputStream(), JobLevel.class).withTemplate(inputStream).sheet("模板").doFill(jobLevelList);
}