通用的导出模板样式

1.controller


@ApiOperation(value = "导出")
    @PostMapping("/getExcel")
    public void getExcel(@RequestBody Conditions query, HttpServletResponse response) {
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        File destFile=null;
        try {
            String fileName = informationStatisticalService.getExcel(query); //query 导出条件
             destFile = new File(fileName.replace("\\","/"));
            //将文件输入
            InputStream inputStream = new FileInputStream(destFile);
            // 设置response参数,可以打开下载页面
            response.reset();
            //设置响应文本格式
            response.setContentType("APPLICATION/OCTET-STREAM;charset=UTF-8");//
//        response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + new String((fileName.substring(fileName.lastIndexOf('/') + 1)).getBytes("gb2312"), "iso-8859-1"));
            //将文件输出到页面
            ServletOutputStream out = response.getOutputStream();
            bis = new BufferedInputStream(inputStream);
            bos = new BufferedOutputStream(out);
            byte[] buff = new byte[1024];
            int bytesRead;
            // 根据读取并写入
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
        } catch (Exception e) {
            e.printStackTrace();


        } finally {
            try {
                if (bis != null) {
                    bis.close();
                }
                if (bos != null) {
                    bos.close();
                }
            } catch (Exception e) {
            }
        }
        destFile.delete();  // excel输出到页面后,删除项目中保存的excel
    }
}

 

2.service.impl

    @Value("${spring.indicator.filePath}")
    private String filePath;  

@Override
    public String getExcel(Conditions query) throws Exception {
        query.setPageIndex(1);
        query.setPageSize(100000);
        IPagination<Map<String, Object>> result = querydata(query);
        List<Map<String, Object>> datas = result.getRecords();
        List<String> head = new ArrayList<>();
        for (String str : query.getCondMap().keySet()) {
            head.add(query.getCondMap().get(str));
        }
        if (filePath.charAt(filePath.length() - 1) != '\\' && filePath.charAt(filePath.length() - 1) != '/') {
            filePath = filePath + "/";
        }
        filePath = filePath.replace("\\", "/");
        //文件不存在,先创建
        File dir = new File(filePath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        //输出文件路径
        StringBuilder outPath = new StringBuilder(filePath).append("统计分析_").append(System.currentTimeMillis()).append(".xls");
        File file = new File(outPath.toString());
        if (file.exists()) {
            return outPath.toString();
        }
        OutputStream os = null;
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFCellStyle style = workbook.createCellStyle();
        HSSFSheet sheet = workbook.createSheet("sheet");
        //style.setAlignment(HorizontalAlignment.CENTER); //水平居中
        style.setAlignment(HorizontalAlignment.LEFT);
        style.setWrapText(false);//自动换行
        HSSFRow row0 = sheet.createRow(0);
        int cellIndex = 1;
        for (String tf : head) {
            //设置宽度
            sheet.setColumnWidth(cellIndex, 1000 * 5);
            HSSFCell cell_00 = row0.createCell(cellIndex);//获取表头对应的cell单元格
            cell_00.setCellStyle(style);
            cell_00.setCellValue(tf);
            cellIndex++;
        }
        for (int i = 0; i < datas.size(); i++) {
            cellIndex = 0;
            row0 = sheet.createRow(i + 1);
            for (String str : query.getCondMap().keySet()) {
                sheet.setColumnWidth(cellIndex, 1000 * 5);
                HSSFCell cell_00 = row0.createCell(cellIndex);
                if (cellIndex == 0) {
                    cell_00.setCellValue(String.valueOf(datas.get(i).get("num")));
                     cellIndex++;
                } else {
                    if (datas.get(i).get(str) != null) {
                        cell_00.setCellValue(String.valueOf(datas.get(i).get(str)));
                    } else {
                        cell_00.setCellValue("");
                    }
                    cellIndex++;
                }
            }
        }
        os = new FileOutputStream(outPath.toString());
        workbook.write(os);
        os.close();
        workbook.close();
        return outPath.toString();
    }

3.application.yml

spring:
  indicator:
    filePath: E:\test

4.pom.xml

    <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.17</version>
        </dependency>

 

整个的导出过程:

在 E:\test 下创建一个 .xls 空文件,把查询后的列表 以数据流的形式 读取到.xls 空文件里
后在controller方法下 加载.xls文件数据流,将数据流读取到 response.getOutputStream()里返回到前端 ,
再删除当前E:\test 目录下 .xls文件

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用EasyExcel可以轻松实现一个通用导出功能。EasyExcel是一个基于Java的开源工具,用于简化Excel操作。可以使用它来读取和写入Excel文件,支持多种数据格式,如List、Map等。 首先,我们需要引入EasyExcel依赖包。可以在maven中央仓库或者GitHub上找到,并添加到项目的pom.xml文件中。然后,我们可以开始编写导出的代码。 首先,我们需要创建一个导出模板,定义Excel的表头。可以使用EasyExcel提供的注解来定义表头的名称、样式等。接着,我们需要编写导出的逻辑。 首先,创建一个导出的工具类,用于处理导出操作。在该工具类中,我们可以定义一个导出方法,该方法接收一个数据列表和一个输出流。 在导出方法中,我们可以使用EasyExcel提供的API来创建一个写入器,并指定要写入的输出流。然后,我们可以使用write方法将数据写入Excel文件。在写入数据之前,可以使用sheet和row方法来创建工作表和行。可以使用cell方法来创建单元格,并使用setValue方法来设置单元格的值。 在导出方法中,我们还可以添加一些导出的配置,如设置自动列宽、设置样式等。可以使用EasyExcel提供的工具类来实现这些功能。 最后,我们可以在程序中调用导出方法,将数据列表和输出流作为参数传递给导出方法即可实现导出功能。 总结起来,使用EasyExcel可以轻松实现一个通用导出功能。我们只需要定义导出模板和数据,然后调用导出方法即可实现导出操作。这个功能可以应用于各种场景,满足不同需求。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值