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

三、效果预览

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

相关推荐
1***t8273 分钟前
将 vue3 项目打包后部署在 springboot 项目运行
java·spring boot·后端
诸葛亮的芭蕉扇32 分钟前
tree组件点击节点间隙的异常问题分析
前端·javascript·vue.js
N***H48640 分钟前
使用Springboot实现MQTT通信
java·spring boot·后端
不努力也不会混1 小时前
vite联邦实现微前端(vite-plugin-federation)
前端·vue.js
Heo1 小时前
原来Webpack在大厂中这样进行性能优化!
前端·javascript·vue.js
涔溪2 小时前
Vue2 项目中通过封装 axios 来同时连接两个不同的后端服务器
前端·vue.js·axios
W***95242 小时前
在Spring Boot项目中使用MySQL数据库
数据库·spring boot·mysql
Q_Q5110082854 小时前
python+django/flask的情绪宣泄系统
spring boot·python·pycharm·django·flask·node.js·php
7***47714 小时前
在2023idea中如何创建SpringBoot
java·spring boot·后端
L***d6705 小时前
十七:Spring Boot依赖 (2)-- spring-boot-starter-web 依赖详解
前端·spring boot·后端