写出使用vue的按钮导出数据为excel文件功能的代码,需要调用接口连接后端数据库,并且使用java语言将后端代码也写出来
时间: 2024-02-01 18:13:52 浏览: 36
前端代码:
```vue
<template>
<div>
<button @click="exportData">导出Excel</button>
</div>
</template>
<script>
import axios from 'axios'
import XLSX from 'xlsx'
export default {
methods: {
async exportData() {
const res = await axios.get('/api/export')
const data = res.data
const worksheet = XLSX.utils.json_to_sheet(data)
const workbook = XLSX.utils.book_new()
XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1')
XLSX.writeFile(workbook, 'data.xlsx')
}
}
}
</script>
```
后端代码(使用Java语言):
```java
@RestController
@RequestMapping("/api")
public class ExportController {
@GetMapping("/export")
public ResponseEntity<byte[]> exportData() {
// 连接数据库,查询数据
List<MyData> dataList = myDataMapper.selectData();
// 转换为Excel文件
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("Sheet1");
int rowNum = 0;
for (MyData data : dataList) {
Row row = sheet.createRow(rowNum++);
Cell cell0 = row.createCell(0);
cell0.setCellValue(data.getField1());
Cell cell1 = row.createCell(1);
cell1.setCellValue(data.getField2());
// ...
}
// 输出Excel文件
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
workbook.write(out);
} catch (IOException e) {
e.printStackTrace();
}
byte[] bytes = out.toByteArray();
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=data.xlsx");
headers.add(HttpHeaders.CONTENT_TYPE, "application/vnd.ms-excel");
headers.add(HttpHeaders.CONTENT_LENGTH, String.valueOf(bytes.length));
return new ResponseEntity<>(bytes, headers, HttpStatus.OK);
}
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)