功能概述
基于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))
}
}
关键点说明
-
后端关键点:
-
使用Apache POI创建Excel文件
-
设置正确的响应头
Content-Type
和Content-Disposition
-
文件名使用URL编码防止中文乱码
-
自动调整列宽提升用户体验
-
-
前端关键点:
-
请求时设置
responseType: 'blob'
接收二进制数据 -
从响应头解析原始文件名
-
使用Blob和URL.createObjectURL实现文件下载
-
下载完成后及时释放内存
-