1,需求
最近甲方提了一个需求,要求导出的excel的单元格式要按要求设定,日期的数据导出日期格式,数字的数据导出数值格式,时间的格式导出时间格式,百分比的数据导出百分比格式
最终效果如图所示:
2,探索
原本使用easypoi框架试了很多次,但导出的数据都是文本格式,后来大佬出手,让我试试easyexcel
easyexcel 官方文档:https://easyexcel./docs/current/quickstart/write
3,撸代码
【实体类】
@Data@JsonInclude(JsonInclude.Include.NON_EMPTY)public class ExcelExportFormatVO {@ExcelProperty(value = "工期",order =9 ,converter = IntegerNumberConverter.class)//用于做excel导入导出private Integer duration;@ColumnWidth(20)@ExcelProperty(value = "计划开始时间",order =10 ,converter = StringToDateConverter.class)//用于做excel导入导出@JsonFormat(pattern = "yyyy/MM/dd", timezone = "GMT+8")private Date start;@ColumnWidth(20)@ExcelProperty(value = "计划结束时间",order =11 ,converter = StringToDateConverter.class)//用于做excel导入导出@JsonFormat(pattern = "yyyy/MM/dd", timezone = "GMT+8")private Date finish;@ExcelProperty(value = "进度",order =16)@NumberFormat("0.00%")private Double overallProgress;;@ColumnWidth(20)@DateTimeFormat("HH:mm:ss")@ExcelProperty(value = "登录时间", order = 18)private Date loginTime;}
注意:
1,一般日期格式使用注解 @DateTimeFormat 就可以设置,当然也可以使用自定义的 StringToDateConverter 用于转换数据格式,
但是需要保证字段的数据类型是Date
2,百分比这里使用注解 @NumberFormat 即可,至于其中的value值可参考excel的数据格式
【自定义转换器编写】
import com.alibaba.excel.converters.Converter;import com.alibaba.excel.metadata.GlobalConfiguration;import com.alibaba.excel.metadata.data.WriteCellData;import com.alibaba.excel.metadata.property.ExcelContentProperty;import com.alibaba.excel.util.WorkBookUtil;import java.util.Date;public class StringToDateConverter implements Converter<Date> {public StringToDateConverter() {}public Class<Date> supportJavaTypeKey() {return Date.class;}public WriteCellData<?> convertToExcelData(Date value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {WriteCellData<?> cellData = new WriteCellData(value);String format = null;if (contentProperty != null && contentProperty.getDateTimeFormatProperty() != null) {format = contentProperty.getDateTimeFormatProperty().getFormat();}//这里可以设置自定义的日期格式WorkBookUtil.fillDataFormat(cellData, format, "yyyy/MM/dd");return cellData;}}
【业务代码-全量导出】
//存放数据List<ExcelExportFormatVO> dataList= new ArrayList<>();//导出数据EasyExcel.write(response.getOutputStream(), ExcelExportFormatVO.class).sheet(fileName).doWrite(dataList);
【业务代码-自定义列导出】
//存放数据List<ExcelExportFormatVO> dataList= new ArrayList<>();//需要导出的列,需要与实体的字段名对应,否则导不出来List<String> fieldList = new ArrayList<>();//导出数据EasyExcel.write(response.getOutputStream(), ExcelExportFormatVO.class).includeColumnFiledNames(fieldList).sheet(fileName).doWrite(dataList);