文章目录
-
-
-
- 一、Excel导出实体类
- 二、自定义样式handler
- 三、servicesImple类中实现方法
- 四、表头设置列宽handler
- 五、Converter转换
一、Excel导出实体类
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.format.DateTimeFormat;
import com.zjn.eng.data.controller.excel.converter.ProcessConverter;
import lombok.Data;
import java.util.Date;
@Data
public class DailyData {
@ExcelProperty("问题描述")
private String problemDescription;
@ExcelProperty("问题提交时间")
@DateTimeFormat("yyyy/MM/dd HH:mm")
private Date submissionTime;
@ExcelProperty("问题提交人")
private String submitter;
@ExcelProperty(value = "是否处理", converter = ProcessConverter.class)
private Integer processingStatus;
@ExcelProperty("事件处理人")
private String transactorName;
}
二、自定义样式handler
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.AbstractVerticalCellStyleStrategy;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import java.util.Arrays;
public class StyleHandler extends AbstractVerticalCellStyleStrategy {
private static String fontName = "等线";
private static Integer[] columnIndex = {1, 2, 3, 4, 7, 8, 9};
@Override
protected WriteCellStyle headCellStyle(Head head) {
WriteCellStyle headWriteCellStyle = new WriteCellStyle();
headWriteCellStyle.setFillForegroundColor(IndexedColors.BLUE_GREY.getIndex());
WriteFont headWriteFont = new WriteFont();
headWriteFont.setFontHeightInPoints((short) 12);
headWriteFont.setFontName(fontName);
headWriteFont.setColor(IndexedColors.WHITE.getIndex());
headWriteCellStyle.setWriteFont(headWriteFont);
headWriteCellStyle.setWrapped(false);
if (Arrays.asList(columnIndex).contains(head.getColumnIndex())) {
headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
} else {
headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.LEFT);
}
headWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
headWriteFont.setBold(true);
return headWriteCellStyle;
}
@Override
protected WriteCellStyle contentCellStyle(Head head) {
WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
if (Arrays.asList(columnIndex).contains(head.getColumnIndex())) {
contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
} else {
contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.LEFT);
}
contentWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
contentWriteCellStyle.setBorderLeft(BorderStyle.THIN);
contentWriteCellStyle.setBorderTop(BorderStyle.THIN);
contentWriteCellStyle.setBorderRight(BorderStyle.THIN);
contentWriteCellStyle.setBorderBottom(BorderStyle.THIN);
WriteFont contentWriteFont = new WriteFont();
contentWriteFont.setFontHeightInPoints((short) 12);
contentWriteFont.setFontName(fontName);
contentWriteCellStyle.setWriteFont(contentWriteFont);
return contentWriteCellStyle;
}
}
三、servicesImple类中实现方法
public void downloadDaily(HttpServletResponse response, DailyVo dailyVo) {
String currentTimeStr = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
String fileName = currentTimeStr + "-日报";
dailyVo.setCurrent(1);
dailyVo.setSize(1000);
Map data = (Map) this.dailyList(dailyVo).getData();
List<Map> records = (List<Map>) data.get("records");
List<DailyData> list = JSON.parseObject(JSON.toJSONString(records), new TypeReference<List<DailyData>>() {
});
try {
OutputStream outputStream = response.getOutputStream();
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
String encodeFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.name());
response.setHeader("Content-Disposition", "attachment;filename=" + encodeFileName + ".xlsx");
ExcelWriter writer = EasyExcel
.write(outputStream)
.registerWriteHandler(new StyleHandler())
.registerWriteHandler(new LongestCellWidthHandler())
.build();
WriteSheet sheet = EasyExcel.writerSheet(0, currentTimeStr + "-日报").head(DailyData.class).build();
writer.write(list, sheet);
writer.finish();
outputStream.flush();
} catch (IOException e) {
log.error("导出用户列表方法失败", e);
}
}
四、表头设置列宽handler
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.style.column.AbstractColumnWidthStyleStrategy;
import org.apache.poi.ss.usermodel.Cell;
import java.util.List;
public class LongestCellWidthHandler extends AbstractColumnWidthStyleStrategy {
@Override
protected void setColumnWidth(WriteSheetHolder writeSheetHolder, List<WriteCellData<?>> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
if (Boolean.TRUE.equals(isHead)) {
int columnWidth = cell.getStringCellValue().length();
columnWidth = Math.max(columnWidth * 5, 20);
if (columnWidth > 255) {
columnWidth = 255;
}
writeSheetHolder.getSheet().setColumnWidth(cell.getColumnIndex(), columnWidth * 256);
}
}
}
五、Converter转换
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.converters.WriteConverterContext;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
public class ProcessConverter implements Converter<Integer> {
@Override
public Class<?> supportJavaTypeKey() {
return Integer.class;
}
@Override
public CellDataTypeEnum supportExcelTypeKey() {
return CellDataTypeEnum.STRING;
}
@Override
public Integer convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
if ("处理中".equals(cellData.getStringValue())) {
return 0;
} else if ("已处理".equals(cellData.getStringValue())) {
return 1;
} else {
return 2;
}
}
@Override
public WriteCellData<String> convertToExcelData(WriteConverterContext<Integer> context) throws Exception {
boolean b = context.getValue() == 0;
if (0 == context.getValue()) {
return new WriteCellData("处理中");
} else if (1 == context.getValue()) {
return new WriteCellData("已处理");
} else {
return new WriteCellData("未处理");
}
}
}