功能介绍

将列表的数据导出成excel文件是管理系统中非常常见的功能。最近正好用到了ElementUI+Vue的组合做了个导出效果,拿出来分享一下,希望可以帮到大家:)

实现效果

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

实现步骤

1.定义导出按钮

 <el-button @click="exportData" type="success" icon="el-icon-download">
 导出数据
 </el-button>

2.定义导出方法

这里提供了2种方式导出,请根据需要自选。

// 导出数据
    exportData() {
      this.$http({
        method: "GET",
        url: "student/export",
        params: {},
        responseType: "blob"
      })
        .then(res => {
          /* 方式1,文件名随机
          let blob = new Blob([res.data], { type: "application/vnd.ms-excel" });
          let url = window.URL.createObjectURL(blob);
          window.location.href = url;
          */
          /* 方式2,支持IE10;文件名自定义
           */
          let blob = new Blob([res.data], { type: "application/vnd.ms-excel" }); // 将服务端返回的文件流(二进制)excel文件转化为blob
          let fileName = "学生列表.xls";

          if (window.navigator && window.navigator.msSaveOrOpenBlob) {
            // IE
            window.navigator.msSaveOrOpenBlob(blob, fileName);
          } else {
            let objectUrl = (window.URL || window.webkitURL).createObjectURL(
              blob
            );
            let downFile = document.createElement("a");
            downFile.style.display = "none";
            downFile.href = objectUrl;
            downFile.download = fileName; // 下载后文件名
            document.body.appendChild(downFile);
            downFile.click();
            document.body.removeChild(downFile); // 下载完成移除元素
            // window.location.href = objectUrl
            window.URL.revokeObjectURL(objectUrl); // 只要映射存在,Blob就不能进行垃圾回收,因此一旦不再需要引用,就必须小心撤销URL,释放掉blob对象。
          }
        })
        .catch(err => {
          console.log(err);
        });
    },

3.定义导出接口

此处以springboot接口为例

/**
     *  导出
     * @param response
     * @throws Exception
     */
    @GetMapping("/export")
    public void export(HttpServletResponse response)  throws Exception{
        // 创建工作簿
        HSSFWorkbook workbook = new HSSFWorkbook();
        // 创建sheet
        HSSFSheet sheet = workbook.createSheet("sheet1");
        String fileName = "学生列表.xls"; // 设置要导出的文件的名字
        // 获取数据集合
        List<Student> list = studentService.list(null);
        // 生成标题行
        HSSFRow row = sheet.createRow(0);
        row.createCell(0).setCellValue("序号");
        row.createCell(1).setCellValue("学号");
        row.createCell(2).setCellValue("姓名");
        row.createCell(3).setCellValue("性别");
        row.createCell(4).setCellValue("身份证");
        row.createCell(5).setCellValue("联系方式");
        row.createCell(6).setCellValue("家庭地址");
        row.createCell(7).setCellValue("班级");
        row.createCell(8).setCellValue("入学日期");
        row.createCell(9).setCellValue("备注");

        Student entity=null;
        for (int i = 0; i < list.size(); i++) {
            entity = list.get(i);
            row = sheet.createRow(i+1); // 从第2行开始填充数据
            // 序号
            row.createCell(0).setCellValue(String.valueOf(i+1));
            row.createCell(1, CellType.STRING).setCellValue(entity.getStudentNo());
            row.createCell(2,CellType.STRING).setCellValue(entity.getStudentName());
            row.createCell(3).setCellValue(entity.getGender().equals("F")?"女":"男");
            row.createCell(4).setCellValue(entity.getIdno());
            row.createCell(5).setCellValue(entity.getPhone());
            row.createCell(6).setCellValue(entity.getAddress());
            row.createCell(7,CellType.STRING).setCellValue(getGradeNameById(entity.getGradeId()));
            row.createCell(8,CellType.STRING).setCellValue(DateUtil.format(entity.getEnrollDate(),"yyyy-MM-dd"));
            row.createCell(9).setCellValue(entity.getRemark());
        }

        response.setContentType("application/octet-stream");
        response.setHeader("Content-disposition",
                "attachment;filename=" + java.net.URLEncoder.encode(fileName, "UTF-8"));
        response.flushBuffer();

        workbook.write(response.getOutputStream());
    }
Logo

前往低代码交流专区

更多推荐