导出数据生成Excel表格
1. 导出实现类
通过export方法导出指定数据为Excel表格文件
/**
导出指定数据为Excel表格
参数1:HttpServletResponse response 必须;浏览器响应;
参数2:QuestVo vo 非必须;请求条件:可以根据请求条件从数据库筛选出需要导出的数据;如果需要导出全部数据库数据,则可以去掉该参数;
参数3:String fileName 必须;导出的Excel文件名称;
*/
@Override
public void export(HttpServletResponse response,QuestVo vo, String fileName) throws IOException {
try{
/**
(1)根据请求条件vo,从数据库内获取符合条件的数据,
(2)再将其转换为需要导出的对象类型
以上两步操作可以封装在getData()方法中执行
ExportAuditInfo(例子)即为要导出的对象类型,从数据库
获得的数据都需要转换成该对象类型才能进行导出;该对象的
定义根据需要自定义
*/
List<ExportAuditInfo> list = getData(vo);
//设置浏览器响应的必要参数
ServletOutputStream out = response.getOutputStream();
response.setContentType("multipart/form-data");
response.setCharacterEncoding("utf-8");
String formFileName = new String(fileName.getBytes("utf-8"), "iso-8859-1");
response.setHeader("Content-Disposition", "attachment;filename=" + formFileName + ".xlsx");
//使用EasyExcel.write进行实际的导出操作
EasyExcel.write(out, ExportAuditInfo.class)
//CustomCellWriteHandler()方法设置Excel文件内表格的宽度为自适应宽度
//createStyleStrategy()方法设置Excel文件的表格样式
.registerWriteHandler(new CustomCellWriteHandler()).registerWriteHandler(this.createStyleStrategy())
.autoCloseStream(true)
//sheet设置了导出的Excel表格的sheet名称
//doWrite方法负责将需要导出的List数据写入Excel中
.sheet("已审核报警数据").doWrite(list);
out.flush();
}catch (Exception e){
LOGGER.error("{},{},{}", DefaultErrorCode.EXCEL_EXPORT_ERROR.getCode(), DefaultErrorCode.EXCEL_EXPORT_ERROR.getMessage(), DefaultErrorCode.EXCEL_EXPORT_ERROR.getContent(),e);
}
}
/**定义CustomCellWriteHandler()方法设置Excel文件内表格的宽度为自适应宽度(可直接复用,无需更改)*/
public class CustomCellWriteHandler extends AbstractColumnWidthStyleStrategy {
private Map<Integer, Map<Integer, Integer>> CACHE = new HashMap<>();
@Override
protected void setColumnWidth(WriteSheetHolder writeSheetHolder, List<CellData> cellDataList, Cell cell, Head head, Integer integer, Boolean isHead) {
boolean needSetWidth = isHead || !CollectionUtils.isEmpty(cellDataList);
if (needSetWidth) {
Map<Integer, Integer> maxColumnWidthMap = CACHE.get(writeSheetHolder.getSheetNo());
if (maxColumnWidthMap == null) {
maxColumnWidthMap = new HashMap<>();
CACHE.put(writeSheetHolder.getSheetNo(), maxColumnWidthMap);
}
Integer columnWidth = this.dataLength(cellDataList, cell, isHead);
if (columnWidth >= 0) {
if (columnWidth > 255) {
columnWidth = 255;
}
Integer maxColumnWidth = maxColumnWidthMap.get(cell.getColumnIndex());
if (maxColumnWidth == null || columnWidth > maxColumnWidth) {
maxColumnWidthMap.put(cell.getColumnIndex(), columnWidth);
writeSheetHolder.getSheet().setColumnWidth(cell.getColumnIndex(), columnWidth * 256);
}
}
}
}
private Integer dataLength(List<CellData> cellDataList, Cell cell, Boolean isHead) {
if (isHead) {
return cell.getStringCellValue().getBytes().length;
} else {
CellData cellData = cellDataList.get(0);
CellDataTypeEnum type = cellData.getType();
if (type == null) {
return -1;
} else {
switch (type) {
case STRING:
return cellData.getStringValue().getBytes().length;
case BOOLEAN:
return cellData.getBooleanValue().toString().getBytes().length;
case NUMBER:
return cellData.getNumberValue().toString().getBytes().length;
default:
return -1;
}
}
}
}
}
/**createStyleStrategy()方法设置Excel文件的表格样式(可直接复用,无需更改)*/
private HorizontalCellStyleStrategy createStyleStrategy(){
// 头的策略
WriteCellStyle headWriteCellStyle = new WriteCellStyle();
// 背景设置为红色
headWriteCellStyle.setFillForegroundColor(IndexedColors.LIGHT_CORNFLOWER_BLUE.getIndex());
WriteFont headWriteFont = new WriteFont();
headWriteFont.setFontHeightInPoints((short)10);
headWriteCellStyle.setWriteFont(headWriteFont);
// 内容的策略
WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
contentWriteCellStyle.setBorderBottom(BorderStyle.THIN); //底边框
contentWriteCellStyle.setBorderLeft(BorderStyle.THIN); //左边框
contentWriteCellStyle.setBorderRight(BorderStyle.THIN); //右边框
contentWriteCellStyle.setBorderTop(BorderStyle.THIN); //顶边框
WriteFont contentWriteFont = new WriteFont();
// 字体大小
contentWriteFont.setFontHeightInPoints((short)10);
contentWriteCellStyle.setWriteFont(contentWriteFont);
// 这个策略是 头是头的样式 内容是内容的样式 其他的策略可以自己实现
HorizontalCellStyleStrategy horizontalCellStyleStrategy =
new HorizontalCellStyleStrategy(headWriteCellStyle,contentWriteCellStyle);
return horizontalCellStyleStrategy;
}
2. 导出实体类ExportAuditInfo
注解@ExcelProperty("")
该注解用来指定Excel表格中的该属性对应的列名称
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。