1.导入依赖
<!-- excel导入导出 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>5.2.5</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.2.5</version> <!-- 版本号根据实际情况进行调整 -->
</dependency>
poi
是用于操作Excel文件的主要库,poi-ooxml
是用于处理Excel中的OOXML格式(.xlsx)文件的扩展库。请根据你的实际情况选择相应的版本号
2. 第一种方式 在浏览器新标签页下载,提供一个链接,下载到指定目录
2.1前端处理
导出excel按钮
<el-button type="success" plain @click="exportExcel" style="margin-left: 10px" icon="el-icon-download">导出Excel</el-button>
绑定事件
//导出数据 exportExcel() { // 发送请求到后端获取Excel数据 axios.defaults.headers['token'] = localStorage.getItem("token"); //将响应数据类型设置为 Blob 对象 原因: 确保文件等二进制数据在传输过程中不会被转换或解析,对于文件下载非常有用,因为你可以直接将返回的二进制数据用于创建可下载的文件 axios.post('http://localhost:8080/excel/exportStation',this.tableData, { responseType: 'blob' }) .then(response => { // 将获取到的Excel数据转换为文件 //Blob是二进制的容器,可以存放任意类型的二进制文件:图片/音频/文件 //type : 类型设为Excel文件(.xlsx)的MIME类型,告诉浏览器创建的是一个Excel文件,默认使用excel打开 const blob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }); // 创建隐藏的下载链接并模拟点击下载 const link = document.createElement('a'); //创建一个可供用户下载的链接 link.href = URL.createObjectURL(blob); link.download = '站点管理.xlsx'; //设置链接的打开方式为新标签页(_blank),这样用户点击链接后会在新标签页中下载文件 link.target = '_blank'; document.body.appendChild(link); link.click(); document.body.removeChild(link); }) .catch(error => { console.error(error); }); },
2.2.后端处理
/**
* 导出站点信息
* @param tableData
* @return
* @throws IOException
*/
@PostMapping(value = "/exportStation", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
public ResponseEntity<byte[]> exportExcelStation(@RequestBody List<Station> tableData) throws IOException {
// 创建Excel工作簿和工作表
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("数据表");
// 添加数据到工作表
Row headerRow = sheet.createRow(0);
headerRow.createCell(0).setCellValue("站点名称");
headerRow.createCell(1).setCellValue("站点类型 ");
headerRow.createCell(2).setCellValue("运营商");
headerRow.createCell(3).setCellValue("车位数量");
headerRow.createCell(4).setCellValue("停车费");
headerRow.createCell(5).setCellValue("充电桩数量");
headerRow.createCell(6).setCellValue("站点状态");
headerRow.createCell(7).setCellValue("图片路径");
Row dataRow;
for (int i = 0; i < tableData.size(); i++) {
dataRow = sheet.createRow(i + 1);
dataRow.createCell(0).setCellValue(tableData.get(i).getStationName());
dataRow.createCell(1).setCellValue(tableData.get(i).getStationType());
dataRow.createCell(2).setCellValue(tableData.get(i).getStationOperator());
dataRow.createCell(3).setCellValue(tableData.get(i).getCarNum());
dataRow.createCell(4).setCellValue(tableData.get(i).getStopCar());
dataRow.createCell(5).setCellValue(tableData.get(i).getPileNum());
dataRow.createCell(6).setCellValue(tableData.get(i).getStationState());
dataRow.createCell(7).setCellValue(tableData.get(i).getStationPicture());
}
// 将工作簿写入字节流(将Excel工作簿写入内存中的字节数组流中)
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
workbook.write(outputStream);
// 设置响应头信息
HttpHeaders headers = new HttpHeaders();
//设置了响应的内容类型为application/octet-stream
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
//浏览器就会提示用户下载文件,并指定文件名为stationExcel.xlsx
headers.setContentDispositionFormData("attachment", "stationExcel.xlsx");
//使用ResponseEntity构建了一个带有响应头和响应体的HTTP响应对象。.ok()表示响应状态码为200,.headers(headers)设置了响应头
// .body(outputStream.toByteArray())设置了响应体为outputStream中的字节数组
return ResponseEntity.ok()
.headers(headers)
.body(outputStream.toByteArray());
}
3.第二种方式:直接下载到本地目录
3.1 前端
只需要提供一个按钮,为其绑定事件,将请求发送给后端就ok了
注意: 1. 如果项目中设有拦截器,不要忘了在请求头中带入token
2. 将想要导出的数据表格传入后端
3.2 后端处理
package com.buba.csms.controller.export;
import com.buba.csms.pojo.station.Station;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
@RestController
@RequestMapping("/excel")
@CrossOrigin
public class ExcelController {
@PostMapping("/export")
public void exportToExcel(HttpServletResponse response, @RequestBody List<Station> tableData) throws IOException {
// 构建Excel文档
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("数据表");
// 设置表头
Row headerRow = sheet.createRow(0);
headerRow.createCell(0).setCellValue("站点名称");
headerRow.createCell(1).setCellValue("站点类型 ");
headerRow.createCell(2).setCellValue("运营商");
headerRow.createCell(3).setCellValue("车位数量");
headerRow.createCell(4).setCellValue("停车费");
headerRow.createCell(5).setCellValue("充电桩数量");
headerRow.createCell(6).setCellValue("站点状态");
headerRow.createCell(7).setCellValue("图片路径");
// 填充数据
Row dataRow;
for (int i = 0; i < 4; i++) {
dataRow = sheet.createRow(i + 1);
dataRow.createCell(0).setCellValue(tableData.get(i).getStationName());
dataRow.createCell(1).setCellValue(tableData.get(i).getStationType());
dataRow.createCell(2).setCellValue(tableData.get(i).getStationOperator());
dataRow.createCell(3).setCellValue(tableData.get(i).getCarNum());
dataRow.createCell(4).setCellValue(tableData.get(i).getStopCar());
dataRow.createCell(5).setCellValue(tableData.get(i).getPileNum());
dataRow.createCell(6).setCellValue(tableData.get(i).getStationState());
dataRow.createCell(7).setCellValue(tableData.get(i).getStationPicture());
}
// 保存到本地文件系统
String filePath = "D:\\ideaProject\\CSMS_Project\\excel\\stationExcel.xlsx";
FileOutputStream outputStream = new FileOutputStream(filePath);
workbook.write(outputStream);
outputStream.close();
// 关闭资源
workbook.close();
}
}
原理是一样的,都是利用了poi来实现对数据的操作,导出到本地指定了下载的具体路径。