1、将后端excel二进制文件导出excel下载
import { read, utils, writeFileXLSX } from "xlsx";const useExportExcel = (excelData: string, fileName: string) => {const wb = read(excelData);const ws = wb.Sheets[wb.SheetNames[0]];// 从工作表生成数据行const data = utils.sheet_to_json(ws);// 从对象数组创建工作表const worksheet = utils.json_to_sheet(data);// 创建新工作簿const workbook = utils.book_new();// 工作表加到工作簿utils.book_append_sheet(workbook, worksheet);writeFileXLSX(workbook, fileName);
};
import { saveAs } from ‘file-saver’; // 适合下图片、文件、压缩包等(就是处理后端返回点击等功能)
const onDownload = async (fileName: string) => {const res = await udfDownload(fileName);const name = fileName.slice(0, fileName.lastIndexOf('-'));saveAs(new Blob([res]), name);
};
下载常用的封装
const downloadFun = (url: string, downloadFileName: string) => {const uint8Array = new Uint8Array(res?.result); // 需要看是否需要处理Uint8Arrayconst zipBlob = new Blob([uint8Array], { type: 'application/zip' });const url = URL.createObjectURL(zipBlob);const downloadLink = document.createElement("a");downloadLink.style.display = "none";downloadLink.download = downloadFileName;downloadLink.href = url;document.body.appendChild(downloadLink);downloadLink.click();document.body.removeChild(downloadLink);window.URL.revokeObjectURL(url);
};
https://blog.csdn.net/Zhuangvi/article/details/121063203(Vue 之 利用new Blob() 对后端返回文件流 或 base64字符串下载导出文件时不同文件类型的 type 值整理及函数封装调用示例)
import JSZip from ‘jszip’; 处理zip文件
function downloadFile(hrefUrl, fileName){let a = document.createElement('a')a.href = hrefUrla.download = fileName // 下载后文件名document.body.appendChild(a)a.click() // 点击下载document.body.removeChild(a) // 下载完成移除元素
}
// 封装blob对象
function dataURLToBlob(base64Str, mimeTypeStr) {let bstr = window.atob(base64Str); // 解码 base-64 编码的字符串,base-64 编码使用方法是 btoa()let length = bstr.length;let u8arr = new Uint8Array(length); // 创建初始化为0的,包含length个元素的无符号整型数组while (length--) {u8arr[length] = bstr.charCodeAt(length); // 返回在指定的位置的字符的 Unicode 编码}return new Blob([u8arr], { type: mimeTypeStr }); // 返回一个blob对象
}
// 后端返回base64公共导出
function downloadFileByBase64(base64Str, mimeTypeStr, fileName){let myBlob = dataURLToBlob(base64Str, mimeTypeStr)let myUrl = window.URL.createObjectURL(myBlob)downloadFile(myUrl, fileName)
}
// 后端返回文件流公共导出
function downloadFileByFileFlow(blobData, mimeTypeStr, fileName) {let blob = new Blob([blobData], { type: mimeTypeStr })let hrefUrl = window.URL.createObjectURL(blob) // 创建下载的链接downloadFile(hrefUrl, fileName);
}