2025.4.15写项目 springboot导入导出excel表和完成接口
今天写后端接口,花了很久的时间去读接口文档,和队友的代码,最后完成第一个子模块前两个后端接口,经postman测试,样例符合接口文档预期
以下为简单的后端excel导入导出模板
/**
* excel 文件导入接口
* @param file excel文件
* @throws Exception
*/
@PostMapping("/import")
public void imp(@RequestBody MultipartFile file) throws Exception {
//1.使用 inputStream 流读取文件
InputStream inputStream = file.getInputStream();
//2.读取流中的数据
ExcelReader reader =ExcelUtil.getReader(inputStream);
//3.将汲取到的数据填充为List
List
//4. 将List导入数据库
userRepository.saveAll(users);
}
/**
* excel导出接口
* @param response
* @param user
* @throws Exception
*/
@GetMapping("/export")
public void export(HttpServletResponse response,User user) throws Exception {
//1.从数据库中查询所有的user数据
List<User> users = userRepository.findAll();
//2.通过工具类将文件写出到浏览器
ExcelWriter writer = ExcelUtil.getWriter(true);
//3.写入数据
writer.write(users, true);
//4.设置响应头 - 修正部分
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
// 正确设置文件名编码(只需编码一次)
String fileName = "用户信息.xlsx";
String encodedFileName = URLEncoder.encode(fileName, "UTF-8")
.replaceAll("\\+", "%20"); // 替换+号为%20以兼容更多浏览器
response.setHeader("Content-Disposition",
"attachment; filename=\"" + encodedFileName + "\";" +
"filename*=UTF-8''" + encodedFileName);
//5.输出流
ServletOutputStream out = response.getOutputStream();
writer.flush(out, true);
out.close();
writer.close();
}
以下为前端内容
<!-- 导入区域 -->
<div class="import-section">
<el-upload
class="upload-demo"
:action="importUrl"
:headers="headers"
:on-success="handleImportSuccess"
:on-error="handleImportError"
:show-file-list="true"
:before-upload="beforeImportUpload"
:file-list="fileList"
:auto-upload="false"
accept=".xlsx,.xls"
drag
@change="handleFileChange"
>
<template #trigger>
<el-button type="primary" :icon="Upload">选择 Excel 文件</el-button>
</template>
<div class="el-upload__text">
将文件拖到此处,或<em>点击选择</em>
</div>
<template #tip>
<div class="el-upload__tip">
支持 .xlsx 或 .xls 格式文件,大小不超过10MB
<el-button
class="ml-3"
type="success"
:icon="Upload"
@click="submitImport"
:loading="importLoading"
:disabled="fileList.length === 0"
>
导入数据
</el-button>
</div>
</template>
</el-upload>
</div>
<!-- 导出区域 -->
<div class="export-section">
<el-button
type="warning"
@click="handleExport"
:icon="Download"
:loading="exportLoading"
>
导出 Excel
</el-button>
</div>
</el-card>

浙公网安备 33010602011771号