SpringBoot导出Excel模板

SpringBoot导出Excel模板

共同探讨,向各位大佬学习
走向CEO,迎娶白富美

pom.xml依赖

<!--excel-->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.11</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.11</version>
        </dependency>

Excel模板文件

在项目resources包下创建templates,将准备好的模板文件放在templates包下。
excel模板文件
在这里插入图片描述

Controller

    @GetMapping("/report")
    public void report(HttpServletResponse response){
        try {
            //从数据库获取数据
            List<User> userList = userMapper.selectList(null);
            //获取Excel模板文件绝对磁盘路径
            String path = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX + "templates/user.xlsx").getPath();
            //基于POI在内存中创建一个Excel文件
            XSSFWorkbook excel= new XSSFWorkbook(new FileInputStream(new File(path)));
            //获取第一个工作表
            XSSFSheet sheet = excel.getSheetAt(0);
            //设置行变量
            int firstNum = 0;
            //遍历集合
            for (User user : userList) {
                //从第二行开始创建新行
                XSSFRow row = sheet.createRow(++firstNum);
                //创建新列,并设值
                row.createCell(0).setCellValue(user.getName());
                row.createCell(1).setCellValue(user.getPassword());
                row.createCell(2).setCellValue(user.getAge());
                row.createCell(3).setCellValue(user.getSex());
            }
            //创建输出流,用于从服务器写数据到客户端浏览器
            ServletOutputStream out = response.getOutputStream();
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("content-Disposition", "attachment;filename=user.xlsx");
            excel.write(out);
            //关闭流
            out.flush();
            out.close();
            excel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

测试

在这里插入图片描述
———————————————————————————————————————
在这里插入图片描述

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值