后端用Easyexcel实现导入和导出excel文件

先导入依赖

        
            com.alibaba
            easyexcel
            2.1.1
        

这里直接展示业务类service代码

因为Controller代码也是直接调用service方法,唯一注意的是要用post请求

导出内容为excel格式

    @Override
    public void exportDictData(HttpServletResponse response) {
        //设置下载信息
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = "dict";
        response.setHeader("Content-disposition", "attachment;filename="+ fileName + ".xlsx");
        //查询数据库
        List list = baseMapper.selectList(null);

        //写入excel 第二个参数是实体类
        try {
            EasyExcel.write(response.getOutputStream(), Dict.class).sheet("dict").doWrite(list);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

导入excel

    @Override
    public void importData(MultipartFile file) {
        try {
            //basemapper是mybatis plus自带的
            EasyExcel.read(file.getInputStream(),Dict.class, new DictListener(baseMapper)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

注意导入的read方法的第三个参数是监听器,需要创建一个监听器

public class DictListener extends AnalysisEventListener {

    private DictMapper dictMapper;
    public DictListener(DictMapper dictMapper) {
        this.dictMapper = dictMapper;
    }

    //一行一行读取
    @Override
    public void invoke(Dict dict, AnalysisContext analysisContext) {
        dictMapper.insert(dict);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}

你可能感兴趣的:(java,spring,boot,maven)