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

       

目录

一、后端(SpringBoot)

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

1.2编写后端逻辑代码

二、前端代码逻辑

三、效果预览

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

一、后端(SpringBoot)

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

        <!-- 导出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中规定导出的文件规范(供前端使用)。

@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类型的响应结果即可。

//导出---导出员工数据
function exportEmployee(){
  return $axios({
    url: `/employee/exportEmpInfo`,
    method: 'get',
    responseType: 'blob'
  })
}
    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
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

龙城桥少

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值