一、后端

1.1、使用工具hutool 读取-ExcelReader

1.2、添加依赖

<!-- https://mvnrepository.com/artifact/cn.hutool/hutool-all -->
<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.7.20</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>4.1.2</version>
</dependency>

1.3、bean中添加toString方法

在这里插入图片描述
excel文件
在这里插入图片描述
数据库表
在这里插入图片描述

1.4、编写controller

//excel导出
    @GetMapping("/exportExcel")
    public void exportExcel(HttpServletResponse response) throws Exception {
        //查询所有数据
        List<User> list = userService.list();
        //在内存操作,写出到浏览器,从浏览器下载
        ExcelWriter writer = ExcelUtil.getWriter(true);
        //自定义标题名
        writer.addHeaderAlias("username", "用户名");
        writer.addHeaderAlias("password", "密码");
        writer.addHeaderAlias("nickname", "昵称");
        writer.addHeaderAlias("email", "邮箱");
        writer.addHeaderAlias("phone", "电话");
        writer.addHeaderAlias("address", "地址");
        writer.addHeaderAlias("createTime", "创建时间");
        writer.addHeaderAlias("avatar", "头像");

        //一次性写出list内的对象到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 outputStream = response.getOutputStream();
        writer.flush(outputStream,true);

        //关闭流
        outputStream.close();
        writer.close();
    }

    //excel导入
    @PostMapping("/importExcel")
    public Boolean importExcel(MultipartFile file) throws IOException {
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);

        //方式1:通过JavaBean的方式读取excel内的对象,但是要求表头必须市英文,和JavaBean属性对应
//        List<User> users = reader.readAll(User.class);

        //方式二:忽略表头中文,直接获取表格数据
        List<List<Object>> list = reader.read(1);
        List<User> users = CollUtil.newArrayList();

        for(List<Object> row:list){
            User user =new User();
            user.setUsername(row.get(1).toString());
            user.setPassword(row.get(2).toString());
            user.setNickname(row.get(3).toString());
            user.setEmail(row.get(4).toString());
            user.setPhone(row.get(5).toString());
            user.setAddress(row.get(6).toString());
            user.setAvatarUrl(row.get(8).toString());

            users.add(user);
        }

        //将excel导入的数据保存到数据库
        userService.saveBatch(users);
        return true;
    }

二、前端

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

Logo

前往低代码交流专区

更多推荐