@Override
public void export(Map<String, Object> params) {
Object resultData = getDataBysqlSteament(params);
List<Map<String, Object>> dataList= (List<Map<String, Object>>) resultData;
Map<String,Object> map = transForExportData(dataList);
List<List<String>> head = (List<List<String>>) map.get("head");
List<List<Object>> data = (List<List<Object>>) map.get("data");
String fileName = "导出数据表.xlsx";
try {
// OutputStream out = new FileOutputStream(fileName);
// ExcelWriter excelWriter = EasyExcel.write(out).build();
//上面的输出流是输出到服务器,单元测试用,下面的输出流是输出到客户端,测试环境生产环境用
response.setHeader("Content-Disposition", "attachment;filename="+fileName);
ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).build();
excelWriter.write(data, EasyExcel.writerSheet().sheetName("导出表").head(head).build());
excelWriter.finish();
} catch (Exception e) {
e.printStackTrace();
}
}
private static Map<String,Object> transForExportData(List<Map<String,Object>> dataList) {
Map<String,Object> map = new HashMap<>();
List<List<String>> head = new ArrayList<>();
List<List<Object>> data = new ArrayList<>();
List<String> headerList = new LinkedList<>(dataList.get(0).keySet());
//构造key
for (String key : headerList) {
head.add(new ArrayList<String>() {{
add(key);
}});
}
//构造data
List<Object> rowDataList = null;
for (Map<String,Object> row : dataList) {
rowDataList = new ArrayList<>();
for (String key : headerList) {
rowDataList.add(row.get(key));
}
data.add(rowDataList);
}
//保存到map返回
map.put("head",head);
map.put("data",data);
return map;
}
导出表格(不用dto当表头,用动态表头)
于 2023-09-27 18:49:51 首次发布