1640天9小时15分52秒

SpringBoot+Vue+EasyExcel实现excel简单导出

1. 先导入EasyExcel依赖

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>easyexcel</artifactId>
            <version>3.1.3</version>
        </dependency>

2. 给实体类上注解,标注导出的excel的表头属性,以及标注无需导出的实体属性

@ExcelProperty("表头单元格名称")    // 标注在需要导出的实体属性上

@ExcelIgnore                       // 标注在无需导出的实体属性上

3. 写后端excel导出通用方法

/**
     * 导出excel
     * @param list 需要导出的数据
     */
    public static <T> void exportExcel(List<T> list, Class<T> clazz) {
        ServletOutputStream outputStream;
        try {
            HttpServletResponse response = ServletUtils.getResponse();
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            outputStream = response.getOutputStream();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        // easyExcel导出的核心代码
        EasyExcel.write(outputStream)
                .head(clazz)
                .excelType(ExcelTypeEnum.XLSX)
                .sheet()
                .doWrite(list);
    }

4. 控制器简单编写示例

/**
     * 导出字典类型excel
     */
    @LogAnnotation(title = "导出字典表格", operateType = OperateType.EXPORT)
    @ApiOperation("导出字典类型excel表格")
    @PostMapping(value = "/exportDictTypeExcel")
    public void exportDictTypeExcel(@RequestBody List<Long> dictTypeIdList){
        List<DictTypeEntity> dictTypeEntityList = dictTypeDao.selectBatchIds(dictTypeIdList);
        ExcelUtils.exportExcel(dictTypeEntityList, DictTypeEntity.class);
    }

5. 前端vue的请求方法

js请求方法代码,需要加上responseType:'blob'
export function exportDictTypeExcel(data) {
    return request({
        url: '/system/dicttype/exportDictTypeExcel',
        method: 'post',
        data,
        responseType:'blob'
    })
}

        vue请求方法代码
        exportDict() {
            var arr = [];
            this.multipleSelection.forEach((row) => arr.push(row.dictId));
            if (arr.length === 0) {
                this.$message({
                    message: "请选择要导出的数据。",
                    type: "error",
                });
            } else {
                this.$confirm("确定导出吗", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "success",
                    callback: (action) => {
                        if (action === "confirm") {
                            //批量导出
                            exportDictTypeExcel(arr).then((res) => {
                            });
                        }
                    },
                });
            }
        },

6. 如果写完以上代码,前后端都能跑通,并且已经有响应的二进制编码,浏览器就是不弹出excel文件下载的弹框,找到你vue的request.js文件,看看请求是否被拦截,
如果被拦截,加上以下代码,即可实现excel导出文件下载的弹框

const contentType = response.headers['content-type'];
    if (contentType == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8") {
      let blob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
      let url = window.URL.createObjectURL(blob);
      const link = document.createElement('a'); // 创建a标签
      link.href = url;
      // link.download = 'test.xlsx';
      link.click();
      URL.revokeObjectURL(url); // 释放内存
      return
    }

posted @   18sui  阅读(2101)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
点击右上角即可分享
微信分享提示