SpringBoot + Vue 用户列表导出功能

功能概述

基于SpringBoot后端和Vue前端的用户列表导出功能,可以将用户数据导出为Excel文件。

技术栈

  • 后端: SpringBoot + Apache POI (Excel操作)

  • 前端: Vue.js + Axios

  • 构建工具: Maven

核心实现

后端实现 (SpringBoot)

1.Maven配置:

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>5.2.3</version>
</dependency>

2.Controller方法:

@GetMapping("/export")
public void exportUsers(
        @RequestParam(required = false) String keyword,
        @RequestParam(defaultValue = "0") int departmentId,
        HttpServletResponse response) throws IOException {
    
    // 设置响应头和文件名
    response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
    String fileName = URLEncoder.encode("用户列表_" + LocalDate.now() + ".xlsx", StandardCharsets.UTF_8);
    response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
​
    // 创建Excel工作簿
    try (Workbook workbook = new XSSFWorkbook()) {
        Sheet sheet = workbook.createSheet("用户列表");
        
        // 创建标题行
        String[] headers = {"用户ID", "用户名","用户昵称","所属部门", "角色"};
        Row headerRow = sheet.createRow(0);
        for (int i = 0; i < headers.length; i++) {
            headerRow.createCell(i).setCellValue(headers[i]);
        }
​
        // 填充数据
        List<User> users = userService.getUsersByPage(1, Integer.MAX_VALUE, keyword, departmentId);
        int rowNum = 1;
        for (User user : users) {
            Row row = sheet.createRow(rowNum++);
            row.createCell(0).setCellValue(user.getId());
            row.createCell(1).setCellValue(user.getUsername());
            row.createCell(2).setCellValue(user.getName());
            row.createCell(3).setCellValue(user.getDepartmentName());
            row.createCell(4).setCellValue(user.getRole());
        }
​
        // 自动调整列宽
        for (int i = 0; i < headers.length; i++) {
            sheet.autoSizeColumn(i);
        }
​
        // 写入响应流
        workbook.write(response.getOutputStream());
    }
}

前端实现 (Vue)

1.API请求方法:

export const userExportService = (params) => {
  return request.get('/user/export', {
    params,
    responseType: 'blob'
  })
}

2.导出功能实现:

const exportUsers = async () => {
    try {
        const response = await userExportService({
            keyword: keyword.value,
            departmentId: 0
        })
​
        // 解析文件名
        const contentDisposition = response.headers['content-disposition']
        let fileName = `用户列表-${new Date().toLocaleDateString()}.xlsx`
        if (contentDisposition) {
            const fileNameMatch = contentDisposition.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/)
            if (fileNameMatch && fileNameMatch[1]) {
                fileName = decodeURIComponent(fileNameMatch[1].replace(/['"]/g, ''))
            }
        }
​
        // 创建下载链接
        const blob = new Blob([response.data], { 
            type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
        })
        const url = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        link.download = fileName
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        window.URL.revokeObjectURL(url)
​
        ElMessage.success('导出成功')
    } catch (error) {
        console.error('导出失败:', error)
        ElMessage.error('导出失败:' + (error.response?.data?.message || error.message))
    }
}

关键点说明

  1. 后端关键点:

    • 使用Apache POI创建Excel文件

    • 设置正确的响应头Content-TypeContent-Disposition

    • 文件名使用URL编码防止中文乱码

    • 自动调整列宽提升用户体验

  2. 前端关键点:

    • 请求时设置responseType: 'blob'接收二进制数据

    • 从响应头解析原始文件名

    • 使用Blob和URL.createObjectURL实现文件下载

    • 下载完成后及时释放内存

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值