欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

springboot+vue实现导出excel,使用easyexcel

程序员文章站 2022-03-15 09:47:51
...

springboot

此处笔记为老版本easyexcel,仅作前端笔记

1.引入依赖
 implementation group: 'com.alibaba', name: 'easyexcel', version: '1.1.2-beat1'
2.代码实现
//导出使用的类
public class ExportClass  {
    //旧版本需要extends BaseRowModel
    @ExcelProperty(value = "姓名", index = 0)
    public String name;
    @ExcelProperty(value = "年龄", index = 1)
    public int age;

    @ExcelProperty(value = "日期", index = 2)
    public Date date;
}

注意:LocalDateTime可能需要转换成Date,我开始使用LocalDateTime导出时候会报错,随后改成Date解决

@RequestMapping("/export")
    @ResponseBody
    public String exporExcel(HttpServletResponse response) throws IOException {
        com.alibaba.excel.ExcelWriter writer = null;
        OutputStream outputStream = response.getOutputStream();
        try {

            response.setHeader("Content-disposition", "attachment; filename=" + "all.xls");
            response.setContentType("application/msexcel;charset=UTF-8");//设置类型
            response.setHeader("Pragma", "No-cache");//设置头
            response.setHeader("Cache-Control", "no-cache");//设置头
            response.setDateHeader("Expires", 0);//设置日期头

            writer = new ExcelWriter(outputStream, ExcelTypeEnum.XLS, true);

            Sheet sheet = new Sheet(1, 0, ExportClass.class);
            sheet.setSheetName("目录");


//            QueryWrapper<Export> queryWrapper = new QueryWrapper<Export>();
//            queryWrapper.like("name","g");
            List<Exportexcel> catagoryList = service.list();
            System.out.println("aaa:"+catagoryList.size());

            List<ExportClass> list=new ArrayList<>();
            for (Exportexcel a : catagoryList){
                ExportClass exportClass = new ExportClass();
                exportClass.name=a.getName();
                exportClass.age=a.getAge();
                exportClass.date=a.getDate();
                list.add(exportClass);
            }
            writer.write(list, sheet);
            writer.finish();

            outputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                response.getOutputStream().close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

//        String fileName = TestFileUtil.getPath() + "repeatedWrite" + System.currentTimeMillis() + ".xlsx";
//        // 这里 需要指定写用哪个class去写
//        ExcelWriter excelWriter = EasyExcel.write(fileName, DemoData.class).build();
//        // 这里注意 如果同一个sheet只要创建一次
//        WriteSheet writeSheet = EasyExcel.writerSheet("模板").build();
//        // 去调用写入,这里我调用了五次,实际使用时根据数据库分页的总的页数来
//        for (int i = 0; i < 5; i++) {
//            // 分页去数据库查询数据 这里可以去数据库查询每一页的数据
//            List<DemoData> data = data();
//            excelWriter.write(data, writeSheet);
//        }
//        // 千万别忘记finish 会帮忙关闭流
//        excelWriter.finish();


        return "index";
    }

前端代码

前端请求头必须要带有responseType: ‘blob’, 把返回值类型

以elementadmin中设置为例子

export function exportExcel(data) {
  return request({
    url: '/exportexcel/export',
    method: 'post',
    data,
    responseType: 'blob'
  })
}

vue页面代码

 exportExcel().then(res =>{
            // const blob = new Blob([res.data],{type: 'application/vnd.ms-excel'});
            // let filename ='1.xls';
            // //创建一个超链接,将文件流赋进去,然后实现这个超链接的单击事件
            // const elink = document.createElement('a');
            // elink.download = filename;
            // elink.style.display = 'none';
            // elink.href = URL.createObjectURL(blob);
            // document.body.appendChild(elink);
            // elink.click();
            // URL.revokeObjectURL(elink.href); // 释放URL 对象
            // document.body.removeChild(elink);
            const dispositionval = res.headers['content-disposition']
            console.log(dispositionval)
            var strs = [] // 定义一数组
            strs = dispositionval.split(';') // 字符分割
            const fname = strs[1].trim()
            var strs2 = []
            strs2 = fname.split('=')
            const filename = strs2[1]
            console.log(filename)

            const url = window.URL.createObjectURL(new Blob([res.data]))
            const link = document.createElement('a')
            link.style.display = 'none'
            link.href = url
            link.setAttribute('download', filename)// 文件名
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link) // 下载完成移除元素
            window.URL.revokeObjectURL(url) // 释放掉blob对象
          }).catch(e=>{
            console.log('失败'+e)
          })
        }

esayexcel新版本

 compile group: 'com.alibaba', name: 'easyexcel', version: '2.2.10'
@RequestMapping("/export")
    @ResponseBody
    public void exporExcel(HttpServletResponse response) throws IOException{
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        OutputStream outputStream = response.getOutputStream();
        try {
            //请求头

            // 这里 需要指定写用哪个class去写,然后写到第一个sheet,名字为模板 然后文件流会自动关闭
            // 如果这里想使用03 则 传入excelType参数即可
//        EasyExcel.write(fileName, ExportClass.class).sheet("模板").doWrite(data());

            // 写法2
//        fileName = TestFileUtil.getPath() + "simpleWrite" + System.currentTimeMillis() + ".xlsx";
            // 这里 需要指定写用哪个class去写
//            ExcelWriter excelWriter = EasyExcel.write(fileName, ExportClass.class).build();
//            WriteSheet writeSheet = EasyExcel.writerSheet("模板").build();
//            excelWriter = new ExcelWriter(outputStream, ExcelTypeEnum.XLS, true);
            List<Exportexcel> catagoryList = service.list();
            List<ExportClass> list=new ArrayList<>();
            for (Exportexcel a : catagoryList){
                ExportClass exportClass = new ExportClass();
                exportClass.name=a.getName();
                exportClass.age=a.getAge();
//                exportClass.date=a.getDate();
                list.add(exportClass);
            }
            //导出
            EasyExcel.write(outputStream, ExportClass.class).sheet().doWrite(list);
            outputStream.flush();

        } finally {
            try {
                response.getOutputStream().close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
相关标签: java vue.js