• 前端导入导出


    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);
    };
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    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);
    };
    
    • 1
    • 2
    • 3
    • 4
    • 5

    下载常用的封装

    const downloadFun = (url: string, downloadFileName: string) => {
      const uint8Array = new Uint8Array(res?.result); // 需要看是否需要处理Uint8Array
      const 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);
    };
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    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 = hrefUrl
        a.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);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30

    // 将表格数据下成excel及合并单元格处理

    		// 表格根据表头数据及表格数据导出excel(目前只有自定义多表格有title  事件表格需要处理快照的合并)
    		const singleAndMultipleTableToExcel = (selectCom: any, multipleTableData: any) => {
    			let worksheet: any;
    			let workbook = XLSXUtils.book_new();
    			multipleTableData?.forEach((tableItem: any, index: number) => {
    				let { title = '', tableHeaderLabel = [], tableHeaderProp = [], tableHeaderPropAttOrigin = [], data = [] } = tableItem || {};
    				// 处理单元格合并(目前快照列表只有事件列表需要处理,其他的返回原数据)
    				let mergeArr: any = [];
    				let currentIndex = (title ? 1 : 0) + (tableHeaderLabel?.length ? 1 : 0); // 行合并{1、无表头无title:0  有表头1  有表头有title 2}
    				const flattenedData = data?.flatMap((item: any) => {
    					const { snapshot = [] } = item;
    					if (snapshot && snapshot?.length > 0) {
    						const result = snapshot?.map((subItem: any) => ({
    							...item,
    							...subItem,
    						}));
    						let mergeFieldName = ['code', 'name']; // 假设处理的是code name字段合并
    						let fieldNameColIndex: any = [];
    						mergeFieldName?.forEach((subFieldName: string) => {
    							fieldNameColIndex.push(tableHeaderProp?.indexOf(subFieldName));
    						});
    						let codeRowStartIndex = currentIndex;
    						let codeRowEndIndex = currentIndex + result.length - 1; // 包含表头如果没有表头需要减1(事件表格一定有表头)
    						fieldNameColIndex?.forEach((subColIndex: number) => {
    							mergeArr.push({ s: { r: codeRowStartIndex, c: subColIndex }, e: { r: codeRowEndIndex, c: subColIndex } });
    						});
    						currentIndex += result.length; // 更新当前索引
    						return result;
    					} else {
    						currentIndex++;
    						return { ...item };
    					}
    				});
    
    				// 按prop的顺序及是否源数据过滤表格数据字段
    				const dataMatrix = flattenedData?.map((item: any) =>
    					tableHeaderProp?.map((prop: any) => (!tableHeaderPropAttOrigin?.includes(prop) ? item?.[prop] : item?.equipAttrAndVal?.[prop]))
    				);
    				if (tableHeaderLabel?.length && title) {
    					worksheet = XLSXUtils.aoa_to_sheet([[title], tableHeaderLabel, ...dataMatrix]);
    				} else if (tableHeaderLabel?.length && !title) {
    					worksheet = XLSXUtils.aoa_to_sheet([tableHeaderLabel, ...dataMatrix]);
    				} else if (tableHeaderLabel?.length == 0 && title) {
    					worksheet = XLSXUtils.aoa_to_sheet([[title], ...dataMatrix]);
    				} else if (tableHeaderLabel?.length == 0 && !title) {
    					worksheet = XLSXUtils.aoa_to_sheet([...dataMatrix]);
    				}
    				if (mergeArr?.length && title) {
    					worksheet['!merges'] = mergeArr?.concat([{ s: { r: 0, c: 0 }, e: { r: 0, c: tableHeaderProp?.length - 1 } }]);
    				} else {
    					mergeArr?.length && (worksheet['!merges'] = mergeArr); // 单元格合并(目前事件表格快照需要处理)
    					title && (worksheet['!merges'] = [{ s: { r: 0, c: 0 }, e: { r: 0, c: tableHeaderProp?.length - 1 } }]); // 有title合并单元格(目前自定义多表格)
    				}
    				XLSXUtils.book_append_sheet(workbook, worksheet, `${title}` || ` Sheet${index + 1}`);
    			});
    			writeFileXLSX(workbook, `${selectCom?.exportButtonConfig?.name || selectCom?.name}.xlsx`);
    		};
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
  • 相关阅读:
    【174】Java解析文件名中的方括号表达式
    正厚软件知识|App测试经典面试题及参考答案
    LLMs:OpenAI官方重磅更新——新增GPT-3.5Turbo调和API更新功能
    VMware虚拟化基础操作实战(基于ESXi6.7 操作系统安装CentOS7.5)
    年龄大了转嵌入式有机会吗?
    Java 包名中包含多个自然单词
    python之图形用户界面,如何安装wxPython
    百度智能云千帆大模型平台2.0来了!从大模型到生产力落地的怪兽级平台!!
    Rust swap
    这C语言代码,会让你发疯
  • 原文地址:https://blog.csdn.net/m0_45127388/article/details/136410804