1. 设置通用样式
java
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.write.style.*;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.xxx.npi.config.easypoi.EasyExcelDateConverter;
import lombok.Data;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import java.util.Date;
@Data
@HeadFontStyle(fontHeightInPoints = 11, fontName = "Calibri", color = 9)
@HeadStyle(fillPatternType = FillPatternType.SOLID_FOREGROUND, fillForegroundColor = 30, leftBorderColor = 22,
rightBorderColor = 22, topBorderColor = 22, bottomBorderColor = 22)
@ContentFontStyle(fontHeightInPoints = 11, fontName = "Calibri")
@ContentStyle(horizontalAlignment = HorizontalAlignment.CENTER, verticalAlignment = VerticalAlignment.CENTER)
@ColumnWidth(16)
@HeadRowHeight(33)
public class TransactionListVo {}
2. 指定字段样式
2.1列宽,表头名称,接口返回样式
java
@ColumnWidth(value = 20)
@ExcelProperty(value = "Transaction Date", converter = EasyExcelDateConverter.class)
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy/MM/dd HH:mm:ss", timezone = "GMT+8")
private Date datetime;
2.2 日期字段,设置输出样式
java
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;
import com.xxx.platform.util.DateUtil;
import java.text.ParseException;
import java.util.Date;
import java.util.Objects;
public class EasyExcelDateConverter implements Converter<Date> {
@Override
public Class supportJavaTypeKey() {
return Date.class;
}
@Override
public CellDataTypeEnum supportExcelTypeKey() {
return CellDataTypeEnum.STRING;
}
@Override
public Date convertToJavaData(CellData cellData, ExcelContentProperty excelContentProperty, GlobalConfiguration globalConfiguration) throws Exception {
return parseDate(cellData);
}
@Override
public CellData convertToExcelData(Date date, ExcelContentProperty excelContentProperty, GlobalConfiguration globalConfiguration) throws Exception {
return new CellData(parseString(date));
}
private Date parseDate(CellData cellData) throws ParseException {
if (cellData.getType() == CellDataTypeEnum.STRING) {
String dateSTR = cellData.getDataFormatString();
Date date = DateUtil.stringToDate(dateSTR, DateUtil.formatStr_yyyyMMddHHmmss);
return date;
}
return null;
}
private String parseString(Date date) throws ParseException {
if (Objects.nonNull(date)) {
String s = DateUtil.dateToString(date, DateUtil.formatStr_yyyyMMddHHmmss_1);
return s;
}
return null;
}
}