vue部分
// 導出計算數據exportDataHandle(id) {this.$http({url: this.$http.adornUrl('/xxx/xxx/exportCalDataExcel'),method: 'post',data: this.$http.adornData({'id': id}),responseType: 'blob', // 重要:告訴axios我們希望接收二進制數據}).then(({data}) => {const blob = new Blob([data], {type: 'data:application/vnd.ms-excel;base64;charset=utf-8'});const downloadElement = document.createElement('a');const href = window.URL.createObjectURL(blob); // 創建下載的鏈接downloadElement.href = href;downloadElement.download = 'abc' + '.xlsx'; // 下載后文件名document.body.appendChild(downloadElement);downloadElement.click(); // 點擊下載document.body.removeChild(downloadElement); // 下載完成移除元素window.URL.revokeObjectURL(href); // 釋放掉blob對象this.$message({message: '操作成功',type: 'success',duration: 1500,})})},
Java部分
1導入maven依賴
這里要注意,由于easyexcel的包中包含了poi的依賴,所以在引入easyexcel包之前,需要刪掉mavne中poi的包,否則會出現依賴異常:com.alibaba.excel.exception.ExcelGenerateException: java.lang.NoSuchFieldError: Factory
<dependency><groupId>com.alibaba</groupId><artifactId>easyexcel</artifactId><version>3.0.5</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.79</version></dependency><dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>5.8.10</version></dependency>
2 編寫代碼
import com.alibaba.excel.EasyExcel; /*** 導出 計算數據*/@RequestMapping("/exportCalDataExcel")public void exportCalDataExcel(@RequestBody ExamEntity exam, HttpServletResponse response) throws IOException {//1 數據獲取List<CalDataDto> dataList = answerScoreService.getAllCalData(exam);//2 設置響應頭response.setContentType("application/vnd.ms-excel");response.setCharacterEncoding("utf-8");// 這里URLEncoder.encode可以防止中文亂碼String fileName = URLEncoder.encode("文件名", "UTF-8").replaceAll("\\+", "%20");response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");// 3 將數據寫入excel中EasyExcel.write(response.getOutputStream(), CalDataDto.class).sheet("Sheet1").doWrite(dataList);}
import com.alibaba.excel.annotation.ExcelProperty;
import lombok.Data;@Data
public class CalDataDto {@ExcelProperty("變量名")
// @ColumnWidth(10)private String name;@ExcelProperty("數據")private Double num;
}