文件以excel格式下载功能实现(SpringBoot+Vue)

目录

一、后端(SpringBoot)

1.1引入导出为表格的工具包依赖

1.2编写后端逻辑代码

二、前端代码逻辑

三、效果预览

最近公司提出了个新寻求,要求把用户管理中的数据导出为excel电子表格,我参考公司项目原有逻辑代码实现了此功能。写一篇文章记录一下,也希望大家伙点赞收藏,以备不时之需。

一、后端(SpringBoot)

1.1引入导出为表格的工具包依赖

XML 复制代码
        <!-- 导出excal文件 -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>5.0.0</version> <!-- 版本号可能会有更新,请使用最新版本 -->
        </dependency>

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>5.0.0</version> <!-- 版本号可能会有更新,请使用最新版本 -->
        </dependency>

1.2编写后端逻辑代码

首先确定被导出表格中的标题行名字,然后根据查出来的数据构建表格中的每一行数据,再把结果存入文件流中进行操作,并通过@Value引入表格导出的理想地址,最后在请求头和ContentType中规定导出的文件规范(供前端使用)。

java 复制代码
@Value("${cj-activityfile.upload.path}")
private String uploadPath;

@Override
    public void exportEmpInfo(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 获取导出数据
        QueryWrapper<Employee> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("create_time");
        List<Employee> employees = employeeMapper.selectList(queryWrapper);
        if (employees.isEmpty()) {
            throw new Exception("对不起,暂无任务数据可导出!");
        }

        SXSSFWorkbook workbook = new SXSSFWorkbook(100); // 缓存100行到内存
        SXSSFSheet sheet = workbook.createSheet("系统用户信息");

        // 创建标题行
        String[] headers = {"员工姓名", "员工账号", "手机号", "账号状态", "性别"};
        int columnIndex = 0;
        SXSSFRow row = sheet.createRow(0);
        for (String header : headers) {
            SXSSFCell cell = row.createCell(columnIndex++);
            cell.setCellValue(header);
        }

        for (int i = 0; i < employees.size(); i++) {
            Employee user = employees.get(i);
            // 总行数加1
            int rowNum = i + 1;

            // 员工姓名
            SXSSFRow row_i = sheet.createRow(rowNum);
            SXSSFCell cell_i_0 = row_i.createCell(0);
            cell_i_0.setCellValue(user.getName());

            // 员工账号
            SXSSFCell cell_i_1 = row_i.createCell(1);
            cell_i_1.setCellValue(user.getUsername());

            // 手机号
            SXSSFCell cell_i_2 = row_i.createCell(2);
            cell_i_2.setCellValue(user.getPhone());

            // 账号状态
            SXSSFCell cell_i_3 = row_i.createCell(3);
            cell_i_3.setCellValue(user.getStatus()==1?"正常":"停用");

            // 性别
            SXSSFCell cell_i_4 = row_i.createCell(4);
            cell_i_4.setCellValue(user.getSex().equals("0")?"女":"男");
        }

        String fileName = "SysUserInfo_" + ".xlsx";
        String filePath = Paths.get(uploadPath, fileName).toString();

        try (FileOutputStream out = new FileOutputStream(filePath)) {
            workbook.write(out);
        }

        try (InputStream is = Files.newInputStream(Paths.get(filePath));
             OutputStream os = response.getOutputStream()) {
            response.setHeader("Content-Disposition",   fileName );
            response.setContentType("application/octet-stream");
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8");

            byte[] b = new byte[1024];
            int length;
            while ((length = is.read(b)) > 0) {
                os.write(b, 0, length);
            }
            os.flush();
        } catch (IOException e) {
            throw new RuntimeException("文件流输出错误!", e);
        } finally {
            workbook.dispose(); // 清除临时文件
        }
    }

二、前端代码逻辑

使用axios与vue完成下载功能,get请求即可,无需传参,只需要告诉后端要返回Blob类型的响应结果即可。

javascript 复制代码
//导出---导出员工数据
function exportEmployee(){
  return $axios({
    url: `/employee/exportEmpInfo`,
    method: 'get',
    responseType: 'blob'
  })
}
javascript 复制代码
    exportDates(){
            this.$confirm('确认确认导出所有账号?', '提示', {
              'confirmButtonText': '确定',
              'cancelButtonText': '取消',
              'type': 'warning'
            }).then(() => {
              exportEmployee().then(response => {
                const blob = response;
                const link = document.createElement('a');
                link.href = window.URL.createObjectURL(blob);
                link.download = "sysUserInfo.xlsx";
                link.click();
                this.$message.success("导出成功!")
              }).catch(err => {
                this.$message.error('请求出错了:' + err)
              })
            })
          },

三、效果预览

点击导出员工数据后,页面右上角显示下载进度。
打开表格,大功告成!

相关推荐
卓怡学长7 小时前
w263基于springboot + vue 健康饮食管理系统
java·数据库·vue.js·spring boot·spring·intellij-idea
无情的西瓜皮8 小时前
MCP 协议实战:从零搭建一个 MCP 服务器(Node.js 版)
vue.js·人工智能·typescript·node.js
万亿少女的梦1688 小时前
基于Spring Boot、Vue.js和MySQL的超市管理系统设计与实现
java·vue.js·spring boot·mysql·管理系统
李明卫杭州9 小时前
Vue2 portal-target 组件与 Vue3 的针对性优化
前端·javascript·vue.js
至乐活着10 小时前
Spring Boot 3.x核心特性深度解析:拥抱Java 17与云原生时代
spring boot·云原生·graalvm·java 17·虚拟线程
Y0011123610 小时前
SpringBoot 基础篇
java·spring boot·spring
江华森11 小时前
Vue Router 与 SPA 原理深度解析
前端·javascript·vue.js
糖墨夕12 小时前
第一章:为什么你要学 AI Agent?—— 从"切图仔"到全栈的进化之路
前端·javascript·vue.js
AC赳赳老秦12 小时前
Excel 动态仪表盘制作:用 OpenClaw 自动处理数据、生成交互式图表并实时更新仪表盘
大数据·服务器·后端·测试用例·excel·deepseek·openclaw