Springboot后端导入导出excel表

 一、依赖添加

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

        
        
            cn.hutool
            hutool-all
            5.7.20
        
        
        
            org.apache.poi
            poi-ooxml
            4.1.2
        

二、实现接口

  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 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 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();
    }

你可能感兴趣的:(springboot,spring,boot,excel,后端)