springboot3+vue3+elementui导入导出
时间: 2025-02-13 08:00:25 浏览: 36
### 实现 Spring Boot 3 和 Vue 3 结合 Element UI 的导入导出功能
#### 后端部分:Spring Boot 3 配置
为了支持 Excel 文件的导入导出,在 `pom.xml` 中添加必要的依赖项[^2]:
```xml
<dependencies>
<!-- Spring Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- MyBatis Plus for ORM -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.1</version>
</dependency>
<!-- Apache POI for Excel handling -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.0.0</version>
</dependency>
<!-- Other dependencies as needed -->
</dependencies>
```
定义控制器来处理上传和下载请求。以下是用于接收文件并保存到数据库以及从数据库读取数据生成 Excel 文件的方法示例。
```java
@RestController
@RequestMapping("/api/excel")
public class ExcelController {
@PostMapping("/upload")
public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) {
try {
// Process the uploaded file and save data to database using service layer.
excelService.importData(file.getInputStream());
return ResponseEntity.ok("Upload successful");
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
}
}
@GetMapping("/download")
public void download(HttpServletResponse response, HttpServletRequest request) throws IOException {
HSSFWorkbook workbook = excelService.exportData();
String fileName = "exported_data.xls";
response.setContentType("application/vnd.ms-excel;charset=utf-8");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8));
ServletOutputStream out = response.getOutputStream();
workbook.write(out);
out.flush();
out.close();
}
}
```
#### 前端部分:Vue 3 和 Element UI 集成
在前端应用中引入 Element UI 并设置全局使用[^1]:
```javascript
import { createApp } from 'vue';
import App from './App.vue';
// Import ElementUI components globally
import ElementPlus from 'element-plus';
import 'element-plus/dist/index.css';
const app = createApp(App);
app.use(ElementPlus);
app.mount('#app');
```
创建一个简单的表单允许用户选择要上载的文件,并通过 API 发送到服务器;同样也提供按钮触发下载操作:
```html
<template>
<div style="margin-top: 20px;">
<el-upload action="/api/excel/upload"
:on-success="handleSuccess">
<el-button type="primary">点击上传</el-button>
</el-upload>
<br><br>
<el-button @click="downloadExcel()">点击下载</el-button>
</div>
</template>
<script setup lang="ts">
import axios from 'axios';
function handleSuccess(response){
ElMessage({
message: '成功',
type: 'success'
});
}
async function downloadExcel(){
await axios.get('/api/excel/download', { responseType: 'blob' })
.then((res)=>{
const url = window.URL.createObjectURL(new Blob([res.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download','data.xlsx');
document.body.appendChild(link);
link.click();
});
}
</script>
```
阅读全文
相关推荐

















