C# Web API下基于axios的xlsx文件下载

avatar
作者
猴君
阅读量:0

服务端代码基于miniexcel库开发

MemoryStream memoryStream = new MemoryStream(); memoryStream.SaveAs(stations.ToList()); memoryStream.Seek(0, SeekOrigin.Begin); return new FileStreamResult(memoryStream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") {     FileDownloadName = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss fff}.xlsx" }; 

前端代码

axios.create({     baseURL: 'https://localhost:7189/',     timeout: 2000,     headers: {         'Content-Type': 'application/json'     } }).post("/tablestation", {         startTime: startTime.value,         endTime: endTime.value,         currentPage: currentPage.value,         pageSize: pageSize.value,         selectionMode: 1     }, {         responseType: 'blob',     }).then((response) => {         // 通过正则表达式获取下载文件名称 	    var filename = ''; 	    var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/; 	    var matches = filenameRegex.exec(response.headers['content-disposition']); 	    if (matches != null && matches[1]) { 	        filename = matches[1].replace(/['"]/g, ''); 	    } 	 	    // 使用blob进行文件下载 	    var blob = new Blob([response.data], { type: response.headers['content-type'] }); 	    if ('msSaveOrOpenBlob' in navigator) { 	        window.navigator.msSaveOrOpenBlob(blob, filename); 	    } else { 	        const link = document.createElement('a'); 	        link.href = window.URL.createObjectURL(blob); 	        link.setAttribute('download', filename); 	        document.body.appendChild(link); 	        link.click(); 	        window.URL.revokeObjectURL(link.href); 	        document.body.removeChild(link); 	    }     })     .catch(function (error) {         console.log(error);     }); 

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!