参考:
https://blog.csdn.net/expect521/article/details/81122642
https://blog.csdn.net/tanwenfang/article/details/90146204
首先在maven中添加依赖:
<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.16</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.16</version> </dependency>
List<ColumnIndex> columnList = aggResult.getColumnList();
List headList = new ArrayList();
for (int i=0;i<columnList.size();i++){
headList.add(columnList.get(i).getName());
}
List dataList = JSONArray.parseArray(JSON.toJSONString(aggResult.getData()));
long startTime = System.currentTimeMillis();
LOG.info("***********downloadExcel startTime:"+startTime);
HSSFWorkbook wb = xlsProcessService.createExcel(headList,dataList);
ByteArrayOutputStream out = new ByteArrayOutputStream();
long endTime = 0;
try {
wb.write(out);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.setContentDispositionFormData("attachment", "table.xls");
endTime = System.currentTimeMillis();
LOG.info("***********downloadExcel endTime:"+endTime);
LOG.info("***********downloadExcel totalTime:"+(endTime-startTime)/1000+"s");
return new ResponseEntity<>(out.toByteArray(), headers, HttpStatus.CREATED);
} catch (IOException e) {
LOG.error("", e);
}
endTime = System.currentTimeMillis();
LOG.info("***********downloadExcel endTime:"+endTime);
LOG.info("***********downloadExcel totalTime:"+(endTime-startTime)/1000+"s");
public HSSFWorkbook createExcel(List headList, List<List<String>> dataList) {
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("sheet1");
sheet.setDefaultColumnWidth(20);
HSSFRow row = sheet.createRow(0);
HSSFCellStyle style = wb.createCellStyle();
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
HSSFCell cell = null;
for (int i = 0; i < headList.size(); i++) {
cell = row.createCell(i);
cell.setCellValue(headList.get(i).toString());
cell.setCellStyle(style);
}
for (int i = 0; i < dataList.size(); i++) {
row = sheet.createRow(i + 1);
List list = dataList.get(i);
for (int j = 0; j < list.size(); j++) {
if (list.get(j) == null) {
row.createCell(j).setCellValue("");
} else {
row.createCell(j).setCellValue(list.get(j).toString());
}
}
}
return wb;
}