實現思路:獲取echars base64圖片------傳參-----在後臺獲取參數---解碼生成圖片輸出到excel
前端代碼:(前端使用的是vue),代碼中的變量需要自己定義
exportData() {
this.exportLoading = true;
let _token = Cookies.get("token");
let _userid = Cookies.get("userId");
let data = {
id: this.$route.params.id,
num: this.dataForm.num,
comId: this.dataForm.comId,
token: _token,
userid: _userid,
baseImgArray: this.baseImgArray
};
let params = qs.stringify(data);
let url =
`${window.SITE_CONFIG["apiURL"]}` +
this.baseUrl.JIEFANG_PROCESS_AUDIT +
`/reporthead/exportData`;
var xhr = new XMLHttpRequest();
xhr.open("post", url, true);
xhr.responseType = "blob";
xhr.setRequestHeader("Content-Type", "application/json;charset=utf-8");
xhr.setRequestHeader("token", _token);
xhr.setRequestHeader("userid", _userid);
xhr.send(JSON.stringify(data));
xhr.onload = function(data) {
console.log(data);
if (this.status == 200) {
var blob = this.response;
var a = document.createElement("a");
var url = window.URL.createObjectURL(blob);
a.href = url;
//設置文件名稱
a.download = "過程審覈報告.xlsx";
a.click();
this.exportLoading = false;
}
};
}
服務端獲取圖片並輸出到excel代碼:
參考鏈接:https://blog.csdn.net/weixin_40076255/article/details/90443928
List<String> baseImgArray = null;
if(null!=params.get("baseImgArray")){
baseImgArray = (List<String>) params.get("baseImgArray");
if(baseImgArray.size() > 0){
short startRow = 1;
int endRow = 15;
for (int i = 0; i <baseImgArray.size() ; i++) {
String baseImg = baseImgArray.get(i);
if(!baseImg.isEmpty()){
String[] imgUrlArr = baseImg.split("base64,");//拆分base64編碼後部分
byte[] buffer = new BASE64Decoder().decodeBuffer(imgUrlArr[1].replaceAll(" ", "+"));
//獲取項目運行目錄的路徑:生成圖片
String picPath = new ClassPathResource("/img").getPath();
log.info("path************************************",picPath);
File file = new File(picPath);//圖片文件
try {
//生成圖片
OutputStream out = new FileOutputStream(file);//圖片輸出流
out.write(buffer);
out.flush();//清空流
out.close();//關閉流
// 將圖片寫入流中
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
BufferedImage bufferImg = ImageIO.read(file);
ImageIO.write(bufferImg, "PNG", outStream);
if (i != 0) {
startRow = (short) (endRow + 5);//開始行
endRow = startRow + 15;//結束行
}
// 利用HSSFPatriarch或XSSFDrawing將圖片寫入EXCEL
XSSFDrawing patri = sheet.createDrawingPatriarch();
//dx1 dy1 起始單元格中的x,y座標.dx2 dy2 結束單元格中的x,y座標//col1,row1 指定起始的單元格,下標從0開 始 //col2,row2 指定結束的單元格 ,下標從0開始
ClientAnchor anchor = new XSSFClientAnchor(5, 10, 255, 255,1, startRow, 10, endRow);
patri.createPicture(anchor, workbook.addPicture(outStream.toByteArray(), XSSFWorkbook.PICTURE_TYPE_PNG));
} catch (Exception ex) {
ex.printStackTrace();
}
if (file.exists()) {
file.delete();//刪除圖片
}
}
}
}
}
導出圖表中遇見的問題: 導出到excel不顯示數據
解決辦法:在setOption中添加 animation: false 參數,作用是取消圖表的動畫效果(參考鏈接:https://blog.csdn.net/WWW_share8/article/details/103679701),如圖: