springboot使用EasyExcel,导出数据到Excel表格,并且将Excel表中数据导入

一、导出至Excel

1.导入依赖

导出方法需要使用到fastJson的依赖,这里也直接导入

点击查看代码
<!--阿里的easyexcel-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>easyexcel</artifactId>
            <version>2.2.0-beta1</version>
            <scope>compile</scope>
        </dependency>
        <!-- 阿里fastjson包JSON转换-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.47</version>
        </dependency>

2.准备导出数据

这里简单创建一个Student的实体类

在导出的数据中,要是不想有某个属性,可以在该属性上面添加@ExcelIgnore注解,

同样,若在导出的数据中想要某个属性,可以在该属性上面添加@ExcelProperty("姓名")注解

若在属性上面啥注解也没有,默认也是会导出该属性的数据,但是表头就是这个属性名。

点击查看实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student implements Serializable {
    private static final long serialVersionUID = 1L;

    @ExcelProperty("Id")
    private String id;

    @ExcelProperty("姓名")
    private String name;

    @ExcelProperty("学号")
    private String studentNo;

    @ExcelProperty("电话")
    private String phone;

    @ExcelProperty("性别")
    private Integer sex;

    @ExcelIgnore
    private Integer age;

    private String h;
}

这里再简单编写一个service方法,模拟查询到的数据;

点击查看Service方法
import java.util.ArrayList;
import java.util.List;

@Service
public class ExportExcelService {

    public List<Student> getData(){
        Student student = new Student("001","张三","191026","13299998888",1,20,"1");
        Student student1 = new Student("002","李四","191027","13299993333",0,20,"1");
        Student student2 = new Student("003","王五","191028","13293338888",1,20,"1");
        return new ArrayList<Student>(){{
            add(student);
            add(student1);
            add(student2);
        }};
    }
}

3.编写controller方法

这里导出的方法就直接写在controller里了,从service查数据。

这里其实需要改动的就只有两个地方,一个就是导出数据集合的泛型,二是导出的数据集合。

EasyExcel.write(response.getOutputStream(), Student.class) .autoCloseStream(Boolean.FALSE) .sheet("导出详情") .doWrite(studentList);

点击查看代码
@RestController
@RequestMapping("/export")
public class ExportExcelController {
    @Autowired
    private ExportExcelService exportExcelService;

    @GetMapping("/")
    public void export(HttpServletResponse response) throws IOException {
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码
            String fileName = URLEncoder.encode("导出", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            List<Student> studentList = exportExcelService.getData();
            // 这里需要设置不关闭流
            EasyExcel.write(response.getOutputStream(), Student.class)
                    .autoCloseStream(Boolean.FALSE)
                    .sheet("导出详情")
                    .doWrite(studentList);
        } catch (Exception e) {
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, String> map = new HashMap();
            map.put("status", "failure");
            map.put("message", "下载文件失败" + e.getMessage());
            response.getWriter().println(JSON.toJSONString(map));
        }
    }
}

4.最后附上效果图

当然,默认的文件名,还有表头的宽高,数据一行的宽高都是可以设置的。都有相应的注解,加在实体类上就可以了,这里就简单逻辑几个:

设置表头的高度:@HeadRowHeight(20)

设置数据的高度:@ContentRowHeight(20)

设置数据的宽度:@ColumnWidth(25)

二、从Excel导入数据

1.依赖

导入和导出使用的依赖都是一样的,只是调用的方法不同,使用一中导入的依赖即可。

2.掉方法

    @SneakyThrows
    @PostMapping("/")
    @ApiOperation(value="导入")
    public List<Student> importData(@RequestPart("file") MultipartFile file) {
        List<Student> studentList = EasyExcel.read(file.getInputStream())
                .head(Student.class)
                .sheet()
                .doReadSync();
        return studentList;
    }

3.测试

posted @   h*z  阅读(1076)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
点击右上角即可分享
微信分享提示