写出使用vue的按钮导出数据为excel文件功能的代码,需要调用接口连接后端数据库,并且使用java语言将后端代码也写出来
时间: 2024-02-01 19:14:02 浏览: 94
前端代码:
```vue
<template>
<div>
<el-button type="primary" @click="exportData">导出数据</el-button>
</div>
</template>
<script>
import axios from 'axios'
export default {
methods: {
exportData() {
axios({
url: '/api/export',
method: 'get',
responseType: 'blob'
}).then(res => {
let blob = new Blob([res.data], { type: 'application/vnd.ms-excel' })
let fileName = 'data.xlsx'
let link = document.createElement('a')
link.href = window.URL.createObjectURL(blob)
link.download = fileName
link.click()
window.URL.revokeObjectURL(link.href)
})
}
}
}
</script>
```
后端代码:
```java
@GetMapping("/export")
public void exportData(HttpServletResponse response) throws IOException {
List<Data> dataList = dataService.getDataList();
String[] titles = { "姓名", "年龄", "性别" };
String fileName = "data.xlsx";
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("sheet1");
XSSFRow row0 = sheet.createRow(0);
for (int i = 0; i < titles.length; i++) {
XSSFCell cell = row0.createCell(i);
cell.setCellValue(titles[i]);
}
for (int i = 1; i <= dataList.size(); i++) {
XSSFRow row = sheet.createRow(i);
Data data = dataList.get(i - 1);
row.createCell(0).setCellValue(data.getName());
row.createCell(1).setCellValue(data.getAge());
row.createCell(2).setCellValue(data.getGender());
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
workbook.write(bos);
byte[] bytes = bos.toByteArray();
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
response.setContentLength(bytes.length);
ServletOutputStream outputStream = response.getOutputStream();
outputStream.write(bytes, 0, bytes.length);
outputStream.flush();
outputStream.close();
}
```
其中,`Data` 是一个实体类,包含 `name`、`age` 和 `gender` 三个属性。`dataService.getDataList()` 是调用服务层方法获取数据列表的代码。在此代码中,使用了 `XSSFWorkbook` 类来创建一个 Excel 工作簿,并且使用 `XSSFSheet` 类来创建一个工作表,最后将数据写入工作表中并导出。
阅读全文