如何批量导出数据到excel并下载,看这一篇就够了,一看就会 您所在的位置:网站首页 腾讯文档收集如何导出数据 如何批量导出数据到excel并下载,看这一篇就够了,一看就会

如何批量导出数据到excel并下载,看这一篇就够了,一看就会

2024-07-15 03:11| 来源: 网络整理| 查看: 265

Excel在开发工作中比较常用的,最近做了一个功能就是批量导出数据到excel,并下载。今天上线了,特将代码贴出来,方便自己以后再做类似功能,能够更快上手,也方便更多没做过Excel功能的童鞋,更快的完成任务。各个层都包含的代码都有哦。 废话不多说 第一步 :导入解析excel需要的pom依赖

org.apache.poi poi 3.14 org.apache.poi poi-ooxml 3.14

第二步:编写controller层代码(根据各自编写各层顺序喜好调整)

@GetMapping("/excelExportWhiteList") public void batchExportWhiteList(HttpServletResponse response) throws IOException { //解决文件名中文乱码 String fileName = "白名单用户信息表" ; OutputStream outputStream=null; Workbook wb=shySaleService.batchExportWhiteList(); //这行代码是固定的,就是说要以excel格式的文件 response.setContentType("application/vnd.ms-excel"); //这一行代码也是大部分是固定的,告诉以附件的形式下载,就 response.setHeader("Content-disposition", "attachment;filename="+new String(fileName.getBytes("gb2312"),"iso-8859-1") + ".xlsx"); outputStream=response.getOutputStream(); //response.setHeader("Content-disposition","attachment;filename="+ URLEncoder.encode("白名单用户信息表.xlsx","utf-8")); outputStream=response.getOutputStream(); wb.write(outputStream); outputStream.flush(); outputStream.close(); }

第三步 :编写service层代码

@Override public Workbook batchExportWhiteList() throws IOException { //查询出所有的白名单用户信息 List list=tabCommodityWhiteListMapper.queryWhiteList(); if (CollectionUtils.isEmpty(list)) { throw new RuntimeException("白名单用户信息为空"); } //创建workbook Workbook workbook = new XSSFWorkbook(); //创建sheet Sheet sheet = workbook.createSheet("白名单用户信息表"); //在sheet中添加表头第0行标题 Row row1 = sheet.createRow(0); Cell ceLL11 = row1.createCell(0); ceLL11.setCellValue("用户名称"); //第一行第二列标题 Cell ceLL12 = row1.createCell(1); ceLL12.setCellValue("手机号码"); //第三列标题 Cell ceLL13 = row1.createCell(2); ceLL13.setCellValue("用户等级"); //需要封装的数据的个数 int length = list.size(); System.out.println("白名单个数"+length); //开始封装数据,因为excel第一行写了标题,所以从1 //开始循环 for (int i = 1; i


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有