文件以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)
              })
            })
          },

三、效果预览

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

相关推荐
JackieDYH3 小时前
vue3中reactive和ref如何使用和区别
前端·javascript·vue.js
伍哥的传说3 小时前
解密 Vue 3 shallowRef:浅层响应式 vs 深度响应式的性能对决
javascript·vue.js·ecmascript·vue3.js·大数据处理·响应式系统·shallowref
前端开发爱好者4 小时前
弃用 html2canvas!快 93 倍的截图神器
前端·javascript·vue.js
就叫飞六吧4 小时前
基于Spring Boot的短信平台平滑切换设计方案
java·spring boot·后端
石国旺7 小时前
前端javascript在线生成excel,word模板-通用场景(免费)
前端·javascript·excel
三贝7 小时前
Java面试实战:Spring Boot微服务在电商场景的技术深度解析
spring boot·redis·微服务·分布式事务·java面试·电商系统·技术面试
Jenna的海糖8 小时前
Vue 项目首屏加载速度优化
前端·javascript·vue.js
前端小巷子8 小时前
最长递增子序列:从经典算法到 Vue3 运行时核心优化
前端·vue.js·面试