700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > js-table2excel导出表格中图片不显示的解决方法

js-table2excel导出表格中图片不显示的解决方法

时间:2022-09-16 20:15:52

相关推荐

js-table2excel导出表格中图片不显示的解决方法

找到node_modules中的js-table2excel里面的index.js,删除原来的代码

改为以下

/* eslint-disable */let idTmr;const getExplorer = () => {let explorer = window.navigator.userAgent;//ieif (explorer.indexOf("MSIE") >= 0) {return 'ie';}//firefoxelse if (explorer.indexOf("Firefox") >= 0) {return 'Firefox';}//Chromeelse if (explorer.indexOf("Chrome") >= 0) {return 'Chrome';}//Operaelse if (explorer.indexOf("Opera") >= 0) {return 'Opera';}//Safarielse if (explorer.indexOf("Safari") >= 0) {return 'Safari';}}// 判断浏览器是否为IEconst exportToExcel = (data, name) => {// 判断是否为IEif (getExplorer() == 'ie') {tableToIE(data, name)} else {tableToNotIE(data, name)}}const Cleanup = () => {window.clearInterval(idTmr);}// ie浏览器下执行const tableToIE = (data, name) => {let curTbl = data;let oXL = new ActiveXObject("Excel.Application");//创建AX对象excellet oWB = oXL.Workbooks.Add();//获取workbook对象let xlsheet = oWB.Worksheets(1);//激活当前sheetlet sel = document.body.createTextRange();sel.moveToElementText(curTbl);//把表格中的内容移到TextRange中sel.select;//全选TextRange中内容sel.execCommand("Copy");//复制TextRange中内容xlsheet.Paste();//粘贴到活动的EXCEL中oXL.Visible = true;//设置excel可见属性try {let fname = oXL.Application.GetSaveAsFilename("Excel.xls", "Excel Spreadsheets (*.xls), *.xls");} catch (e) {print("Nested catch caught " + e);} finally {oWB.SaveAs(fname);oWB.Close(savechanges = false);//xls.visible = false;oXL.Quit();oXL = null;// 结束excel进程,退出完成window.setInterval("Cleanup();", 1);idTmr = window.setInterval("Cleanup();", 1);}}// 非ie浏览器下执行const tableToNotIE = (function () {// 编码要用utf-8不然默认gbk会出现中文乱码const uri = 'data:application/vnd.ms-excel;base64,',template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="/TR/REC-html40"><head><meta charset="UTF-8"><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>';const base64 = function (s) {return window.btoa(unescape(encodeURIComponent(s)));}const format = (s, c) => {return s.replace(/{(\w+)}/g,(m, p) => {return c[p];})}return (table, name) => {const ctx = {worksheet: name,table}const url = uri + base64(format(template, ctx));if (navigator.userAgent.indexOf("Firefox") > -1) {window.location.href = url} else {const aLink = document.createElement('a');aLink.href = url;aLink.download = name || '';let event;if (window.MouseEvent) {event = new MouseEvent('click');} else {event = document.createEvent('MouseEvents');event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);}aLink.dispatchEvent(event);}}})()// 导出函数const table2excel = async (column, data, excelName) => {const typeMap = {image: getImageHtml,text: getTextHtml}let thead = column.reduce((result, item) => {result += `<th>${item.title}</th>`return result}, '')thead = `<thead><tr>${thead}</tr></thead>`var tbody = ``for (var item of data) {var temp = ``for (var item1 of column) {temp += await typeMap[item1.type || 'text'](item[item1.key], item1)}tbody += `<tr>${temp}</tr>`}tbody = `<tbody>${tbody}</tbody>`const table = thead + tbody// console.log(table)// 导出表格exportToExcel(table, excelName)function getTextHtml (val) {return new Promise((resolve, reject) => {resolve(`<td style="text-align: center;vnd.ms-excel.numberformat:@">${val}</td>`)})// return `<td style="text-align: center;vnd.ms-excel.numberformat:@">${val}</td>`}function imgUrlToBase64 (url) {return new Promise((resolve, reject) => {if (!url) {resolve('')}if (/\.(png|jpe?g|gif|svg)(\?.*)?$/.test(url)) {// 图片地址const image = new Image()// 设置跨域问题image.setAttribute('crossOrigin', 'anonymous')// 图片地址image.src = urlimage.onload = () => {const canvas = document.createElement('canvas')const ctx = canvas.getContext('2d')canvas.width = image.widthcanvas.height = image.heightctx.drawImage(image, 0, 0, image.width, image.height)// 获取图片后缀const ext = url.substring(url.lastIndexOf('.') + 1).toLowerCase()// 转base64const dataUrl = canvas.toDataURL(`image/${ext}`)resolve(dataUrl || '')}} else {// 非图片地址resolve('非(png/jpe?g/gif/svg等)图片地址');}})}function getImageHtml (val, options) {return new Promise((resolve, reject) => {imgUrlToBase64(val).then(res => {options = Object.assign({ width: 40, height: 60 }, options)resolve(`<td style="width: ${options.width}px; height: ${options.height}px; text-align: center; vertical-align: middle"><img src="${res}" width=${options.width} height=${options.height}></td>`)}).catch(e => {resolve(e)})})}}export default table2excel

一些网络地址的图片在导出时需要等待异步加载完成之后再转为base64赋值给img标签中的src属性

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。