导出Excel工具类
Posted onestriver
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了导出Excel工具类相关的知识,希望对你有一定的参考价值。
导出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文件中
以上是关于导出Excel工具类的主要内容,如果未能解决你的问题,请参考以下文章
几行代码就能实现复杂的 Excel 导入导出,这个工具类真心强大!