Springboot后端导入导出excel表

 一、依赖添加

操作手册:Hutool — 🍬A set of tools that keep Java sweet.

        <!--hutool工具包-->
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.7.20</version>
        </dependency>
        <!--Apache POI,用于读写excel文档-->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>4.1.2</version>
        </dependency>

二、实现接口

  excel导入
    /**
     * 上传excel
     * @param file 请求头设置为form-data,参数名需一致(例如:file)
     * @throws Exception
     */
    @PostMapping("/import")
    public void importExcel(MultipartFile file) throws Exception {
        // 获取数据流
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        
        // 读取数据
        List<Login> list = reader.readAll(Login.class);
        System.out.println(list);
    }
 excel导出
    /**
     * 导出excel
     * @param response
     * @throws Exception
     */
    @GetMapping("/export")
    public void exportExcel(HttpServletResponse response) throws Exception {
        List<Login> list = loginService.list();

        // 从内存操作,直接写出到浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);

        // 自定义列名
        writer.addHeaderAlias("id", "账号");
        writer.addHeaderAlias("name", "用户名");
        writer.addHeaderAlias("job", "职业");
        writer.addHeaderAlias("address", "地址");

        // 写出到excel对象
        writer.write(list, true);

        // 设置浏览器响应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("用户信息表", "UTF-8");
        response.setHeader( "Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        // 执行导出,并释放
        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        out.close();
        writer.close();
    }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值