导出Excel的工具方法,主要是生成excel文件:
public static void writeFailureReasonToExcelFile(List<FailureReasonResponseEntity> queryAllFailureReasonCountList,String path){ try { //创建一个工作簿 excel文件 XSSFWorkbook workbook = new XSSFWorkbook(); //创建一个标签页 XSSFSheet sheet = workbook.createSheet("失败原因查询数据"); //创建标题行 XSSFRow xSSFRow = sheet.createRow(0); xSSFRow.createCell(0).setCellValue("波束号"); xSSFRow.createCell(1).setCellValue("单位"); xSSFRow.createCell(2).setCellValue("主叫号码"); xSSFRow.createCell(3).setCellValue("被叫号码"); xSSFRow.createCell(4).setCellValue("失败原因"); //将数据写入Excel表格中 for (FailureReasonResponseEntity failureReasonResponseEntity : queryAllFailureReasonCountList) { XSSFRow dataRow = sheet.createRow(sheet.getLastRowNum()+1); dataRow.createCell(0).setCellValue(failureReasonResponseEntity.getBeamId()); dataRow.createCell(1).setCellValue(failureReasonResponseEntity.getLevelUnit()); dataRow.createCell(2).setCellValue(failureReasonResponseEntity.getCallerResponseNumber()); dataRow.createCell(3).setCellValue(failureReasonResponseEntity.getCalleeResponseNumber()); dataRow.createCell(4).setCellValue(failureReasonResponseEntity.getReasonResponseValue()); } FileOutputStream os = new FileOutputStream(path); workbook.write(os); //关闭流 os.close(); workbook.close(); } catch (Exception e) { e.printStackTrace(); } }
controller层的处理方法:
@RequestMapping("/getOptionQueryData") @RequiresPermissions("sys:failureReason:getOptionQueryData") public void getOptionQueryData(HttpServletResponse response) throws Exception { if(queryAllFailureReasonCountList.size()!=0){ //将查询出来的数据写到Excel文件中 //输出流进行文件下载 String fileName = "FailureReasonCount_"+sdf.format(new Date())+".xlsx"; File file = new File(fileName); //将数据写入Excel中 ExcelUtils.writeFailureReasonToExcelFile(queryAllFailureReasonCountList,fileName); // 以流的形式下载文件。 FileInputStream fileInputStream = new FileInputStream(file); String encodedfileName = new String(fileName.getBytes(), "UTF-8"); response.setHeader("Content-Disposition", "attachment; filename=\"" + encodedfileName + "\""); IOUtils.copy(fileInputStream, response.getOutputStream()); fileInputStream.close(); } }
通过上面的代码就能实现导出到excel文件中
原文地址:https://www.cnblogs.com/OneStriver/p/9442322.html
时间: 2024-10-06 07:15:06