后端导出excel 前端
时间: 2025-05-14 14:38:45 浏览: 21
### 实现Excel导出功能的前后端最佳实践
#### 后端实现(Spring Boot)
为了实现在后端通过接口导出 Excel 文件的功能,可以利用 Apache POI 库来创建并写入数据到 Excel 表格中。下面是一个简单的 Spring Boot 控制器方法用于处理请求并将生成好的 Excel 文件作为响应返回给客户端。
```java
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
@RestController
@RequestMapping("/api/export")
public class ExportController {
@GetMapping(value = "/excel", produces = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
public void exportToExcel(HttpServletResponse response) throws IOException {
// 设置HTTP响应头信息
String fileName = URLEncoder.encode("example.xlsx", "UTF-8");
response.setContentType("application/octet-stream;charset=UTF-8");
response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
try (Workbook workbook = new SXSSFWorkbook(); OutputStream outputStream = response.getOutputStream()) {
Sheet sheet = workbook.createSheet("Data");
Row headerRow = sheet.createRow(0);
CellStyle cellStyle = workbook.createCellStyle();
// 创建表头样式
Font font = workbook.createFont();
font.setBold(true);
cellStyle.setFont(font);
// 添加列名
String[] headers = {"ID", "Name"};
for (int i = 0; i < headers.length; i++) {
Cell cell = headerRow.createCell(i);
cell.setCellValue(headers[i]);
cell.setCellStyle(cellStyle);
}
// 填充一些模拟的数据行
Object[][] data = {{"1", "Alice"}, {"2", "Bob"}};
int rowNum = 1;
for (Object[] rowData : data) {
Row row = sheet.createRow(rowNum++);
for (int colIndex = 0; colIndex < rowData.length; colIndex++) {
Cell cell = row.createCell(colIndex);
cell.setCellValue((String) rowData[colIndex]);
}
}
// 将工作簿写出至输出流
workbook.write(outputStream);
} catch (Exception e) {
throw new RuntimeException(e.getMessage(), e);
}
}
}
```
此代码片段展示了如何设置 HTTP 头部以便浏览器能够识别这是一个文件下载操作,并指定了文件名为 `example.xlsx`[^1]。
#### 前端调用(Vue.js)
对于前端部分,在 Vue 组件内可以通过发起 AJAX 请求的方式向服务器发送指令以触发文件下载动作。这里推荐使用 axios 来简化网络通信过程:
```javascript
<template>
<!-- ... -->
</template>
<script setup lang="ts">
import axios from 'axios';
const downloadFile = async () => {
const url = '/api/export/excel';
await axios({
method: 'GET',
url,
responseType: 'blob', // Important to specify this option so that the file can be downloaded correctly.
}).then(response => {
const blob = new Blob([response.data], { type: 'application/vnd.ms-excel' });
// Create a link element and simulate click event on it to trigger browser's native save dialog box.
let link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = 'exported_data.xlsx'; // Set desired filename here.
document.body.appendChild(link); // Add temporary anchor tag into DOM tree temporarily.
link.click();
setTimeout(() => {
window.URL.revokeObjectURL(link.href); // Clean up after ourselves by revoking object URLs when no longer needed.
document.body.removeChild(link);
}, 100);
}).catch(error => console.error(`Error downloading file ${error}`));
};
// Bind function call to button or other UI elements as necessary...
</script>
```
这段脚本说明了怎样配置 Axios 的 GET 请求参数以及如何处理接收到的二进制大对象 (`Blob`) 数据,从而启动用户的本地保存对话框[^2]。
阅读全文
相关推荐

















