vue+table2excel 导出JSON数据到excle

最近在做一个信息采集管理系统,需要把采集到的信息导出到excle,先说说在vue中安装和引入table2excel  

//安装
npm install js-table2excel

//引入
import table2excel from 'js-table2excel'

 

采集系统需要收集的信息包含姓名、手机号、身份证号、还有一项是上传图片;

模拟数据如下:

const data=[
    {
        name:"张三",
        phone:"13512345678",
        idCard:"412356198601251234",
        image:"https://profile.csdnimg.cn/9/8/3/2_xiaoxiaojie12321"
    },
    {
        name:"李四",
        phone:"13612345678",
        idCard:"412356198601251234",
        image:"https://profile.csdnimg.cn/9/8/3/2_xiaoxiaojie12321"
    },
    {
        name:"王五",
        phone:"13712345678",
        idCard:"412356198601251234",
        image:"https://profile.csdnimg.cn/9/8/3/2_xiaoxiaojie12321"
    }
]

需求是导出时将图片一块导出 

下面是导出按钮上绑定的方法

exportExcel() {

      const column=[
        {
          title: '姓名',
          key: 'name',
          type: 'text'
        },
        {
          title: '手机号',
          key: 'phone',
          type: 'text'
        },
        {
          title: '身份证号',
          key: 'idCard',
          type: 'text'
        },
        {
          title: '图片',
          key: 'image',
          type: 'image',
          width: 80,
          height: 50
        },
      ]

      /** column数据的说明 */
      // 1.title为列名
      // 2.key为data数据每个对象对应的key
      // 3.若为图片格式, 需要加type为image的说明,并且可以设置图片的宽高
      const data = this.tableData
      const excelName = `人员信息统计表`
      table2excel(column, data, excelName)
}

本人亲测,这样确实可以导出数据中的图片,但是又出现了一个新问题,导出表格内的身份证号码显示成了科学计数法,这肯定不符合要求,找了半天的资料,也没找到一个合适的案例,后面收到网友提供的方法启发,才解决;

网友提供的方法如下:

只需在td上加上如下style, 

<td style="mso-number-format:'\@';" ng-bind="data.paySerialNo"></td>

可是我想了半天,我是通过JSON数据导出的,我改吧这个代码加到哪儿;无奈之下准备去看看依赖代码:

源码文件路径  :node_modules\js-table2excel\index.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会出现中文乱码
	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="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>';

	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 = (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>`

	let tbody = data.reduce((result, row) => {
		const temp = column.reduce((tds, col) => {
			tds += typeMap[col.type || 'text'](row[col.key], col)
			return tds
		}, '')
		result += `<tr>${temp}</tr>`
		return result
	}, '')

	tbody = `<tbody>${tbody}</tbody>`

	const table = thead + tbody

	// 导出表格
	exportToExcel(table, excelName)

	function getTextHtml(val) {
        //在此处生成单元格时添加上述样式属性
		return `<td style="text-align: center;vnd.ms-excel.numberformat:@">${val}</td>`
	}

	function getImageHtml(val, options) {
		options = Object.assign({width: 40, height: 60}, options)
		return `<td style="width: ${options.width}px; height: ${options.height}px; text-align: center; vertical-align: middle"><img src="${val}" width=${options.width} height=${options.height}></td>`
	}
}

export default table2excel

好嘞,搞完这个就结束了

 

另附:其他的单元格样式属性 

mso-number-format:"0"    NO Decimals
mso-number-format:"0\.000"    3 Decimals
mso-number-format:"\#\,\#\#0\.000"    Comma with 3 dec
mso-number-format:"mm\/dd\/yy"    Date7
mso-number-format:"mmmm\ d\,\ yyyy"    Date9
mso-number-format:"m\/d\/yy\ h\:mm\ AM\/PM"    D -T AMPM
mso-number-format:"Short Date"    01/03/1998
mso-number-format:"Medium Date"    01-mar-98
mso-number-format:"d\-mmm\-yyyy"    01-mar-1998
mso-number-format:"Short Time"    5:16
mso-number-format:"Medium Time"    5:16 am
mso-number-format:"Long Time"    5:16:21:00
mso-number-format:"Percent"    Percent - two decimals
mso-number-format:"0%"    Percent - no decimals
mso-number-format:"0\.E+00"    Scientific Notation
mso-number-format:"\@"    Text
mso-number-format:"\#\ ???\/???"    Fractions - up to 3 digits (312/943)
mso-number-format:"\0022£\0022\#\,\#\#0\.00"    £12.76
mso-number-format:"\#\,\#\#0\.00_ \;
Red
Red
\-\#\,\#\#0\.00\ "    
2 decimals, negative numbers in red and signed (1.56   -1.56)

 

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值