JavaScript导出图片和数据到Excel

JavaScript导出图片和数据到Excel

 

以下方法可以利用json数据将图片地址生成图片导出到Excel,同样也可以将数据导出到Excel。解决网上许多方法关于导出图片到Excel却无法让图片在单元格内显示的问题,也解决了各类浏览器兼容问题。话不多少,先上车吧(哈哈)

 

1、目录结构

2、在页面中引入export2Excel.js文件

将tHeader和tbody作为参数调用export2Excel函数,就可以导出Excel了。

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>导出图片和数据到Excel</title>
</head>
<body>
</body>
<script src="export2Excel.js"></script>
<script>
    // tHeader和tbody的数据需要一一对应
    let tHeader = [
		'鲜花',
		'颜色',
		'照片'
	]
	let tbody = [
		{
			name: '玫瑰花',
			color: '红色',
			pic: 'https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=2801998497,4036145562&fm=27&gp=0.jpg'
		},
		{
			name: '菊花',
			color: '黄色',
			pic: 'https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=1506844670,1837003941&fm=200&gp=0.jpg'
		},
		{
			name: '牵牛花',
			color: '紫色',
			pic: 'https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=3056120770,1115785765&fm=27&gp=0.jpg'
		},
		{
			name: '梅花',
			color: '白色',
			pic: 'https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=2700343322,3431874915&fm=27&gp=0.jpg'
		},
		{
			name: '桃花花',
			color: '粉色',
			pic: 'https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=602076004,4209938077&fm=27&gp=0.jpg'
		}
	]
	export2Excel(tHeader, tbody, '我爱花朵')
</script>
</html>

 3、导出的Excel表格

4、VUE导出

如果在vue中使用的话,可以将export2Excel.js最后一个导出函数前面加上export,然后在使用的页面中将其导入就可以使用了。路径写自己目录中的路径

export2Excel.js文件

/* eslint-disable */
let idTmr;
const getExplorer = () => {
  let explorer = window.navigator.userAgent;
  //ie
  if (explorer.indexOf("MSIE") >= 0) {
    return 'ie';
  }
  //firefox
 
  else if (explorer.indexOf("Firefox") >= 0) {
    return 'Firefox';
  }
  //Chrome
  else if (explorer.indexOf("Chrome") >= 0) {
    return 'Chrome';
  }
  //Opera
  else if (explorer.indexOf("Opera") >= 0) {
    return 'Opera';
  }
  //Safari
  else if (explorer.indexOf("Safari") >= 0) {
    return 'Safari';
  }
}
// 判断浏览器是否为IE
const exportToExcel = (data,name) => {
 
  // 判断是否为IE
  if (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对象excel
  let oWB = oXL.Workbooks.Add();
  //获取workbook对象
  let xlsheet = oWB.Worksheets(1);
  //激活当前sheet
  let 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会出现中文乱码
  let 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="http://www.w3.org/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>',
    base64 = function(s) {
      return window.btoa(unescape(encodeURIComponent(s)));
 
    },
 
    format = (s, c) => {
      return s.replace(/{(\w+)}/g,
        (m, p) => {
          return c[p];
        })
    }
  return (table, name) => {
    let ctx = {
      worksheet: name,
      table
    }
 
    //创建下载
    let link = document.createElement('a');
    link.setAttribute('href', uri + base64(format(template, ctx)));
 
    link.setAttribute('download', name);
 
 
    // window.location.href = uri + base64(format(template, ctx))
    link.click();
  }
})()
 
// 导出函数
const export2Excel = (theadData, tbodyData, dataname) => {
 
  let re = /http/ // 字符串中包含http,则默认为图片地址
  let th_len = theadData.length // 表头的长度
  let tb_len = tbodyData.length // 记录条数
  let width = 40 // 设置图片大小
  let height = 60
 
  // 添加表头信息
  let thead = '<thead><tr>'
  for (let i = 0; i < th_len; i++) {
    thead += '<th>' + theadData[i] + '</th>'
  }
  thead += '</tr></thead>'
 
  // 添加每一行数据
  let tbody = '<tbody>'
  for (let i = 0; i < tb_len; i++) {
    tbody += '<tr>'
    let row = tbodyData[i] // 获取每一行数据
 
    for (let key in row) {
      if (re.test(row[key])) { // 如果为图片,则需要加div包住图片
        // 
        tbody += '<td style="width:' + width + 'px; height:' + height + 'px; text-align: center; vertical-align: middle"><div style="display:inline"><img src=\'' + row[key] + '\' ' + ' ' + 'width=' + '\"' + width + '\"' + ' ' + 'height=' + '\"' + height + '\"' + '></div></td>'
      } else {
        tbody += '<td style="text-align:center">' + row[key] + '</td>'
      }
    }
    tbody += '</tr>'
  }
  tbody += '</tbody>'
 
  let table = thead + tbody
 
  // 导出表格
  exportToExcel(table, dataname)
}

根据实际开发需要,可以对导出函数进行相应的改动,比如向让表格生成编号,可以在导出函数里添加一行代码

这样就可以生成编号了

还可以通过改变width和height的大小得到相应大小的图片。

 

如果大家在使用的过程中遇到问题,可以给本同学留言,我们来一起探讨。这个导出方法为作者根据网络资料进行改进,如需转载,请联系博主。

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值