在网上参考了很多的使用js导出excel表格的案例,但是个人感觉都讲的不是特别好。我这边也自己实现了一个
实现步骤:
直接上代码!
function exportToExcel(){
let columnList = [
{
"header": "详细地址\n",
"field": "address",
},
{
"header": "地址派送方式\n",
"field": "addressDeliveryType",
}
]; //表头部分
let bodyList = [
{
"address": "xxxxx,xxxxxxxxxxxxxx",
"addressDeliveryRemark": "该地址暂无网点派送",
"addressDeliveryType": "盲区",
"allDeliveryArea": "",
"city": "xxx",
"county": "xxx",
"message": "OK",
"noDeliveryArea": "",
"province": "xxx",
"siteName": "地址匹配出的网点为空,请核对地址",
"siteNameAddress": "",
"siteServicesTy": "",
"siteStatus": "",
"status": "1",
"town": "xxx",
"townDispatch": "xxxx",
"_id": 55,
"_uid": 55
},
{
"address": "海女,xxxxxxx,浙江省xxxxxxxxxxxxxxx",
"addressDeliveryRemark": "该地址暂无网点派送",
"addressDeliveryType": "盲区",
"allDeliveryArea": "",
"city": "xxxx",
"county": "xxx",
"message": "OK",
"noDeliveryArea": "",
"province": "xxx",
"siteName": "地址匹配出的网点为空,请核对地址",
"siteNameAddress": "",
"siteServicesTy": "",
"siteStatus": "",
"status": "1",
"town": "xxx",
"townDispatch": "xxxx",
"_id": 56,
"_uid": 56
}];
//拿到的集合
let excelList = [];
for (var i = 0; i < columnList.length; i++) {
// 一行一行数据分割开
excelList.push(exportFormat(columnList[i].header)+",");
}
excelList.push('\n')
for (var i = 0; i < bodyList.length; i++) {
excelList.push(exportFormat(bodyList[i].address)+",")
excelList.push(exportFormat(bodyList[i].addressDeliveryType)+",")
excelList.push(exportFormat(bodyList[i].addressDeliveryRemark)+",")
excelList.push(exportFormat(bodyList[i].siteName)+",")
excelList.push(exportFormat(bodyList[i].siteNameAddress)+",")
excelList.push(exportFormat(bodyList[i].province)+",")
excelList.push(exportFormat(bodyList[i].city)+",")
excelList.push(exportFormat(bodyList[i].county)+",")
excelList.push(exportFormat(bodyList[i].town)+",")
excelList.push(exportFormat(bodyList[i].townDispatch)+",")
excelList.push("\n");
}
var merged = excelList .join("");//将上述得到的excel集合,转化为excel表格中的需要使用的字符串
//## 导出操作
// encodeURIComponent解决中文乱码
const uri =
"data:text/xlsx;charset=utf-8,\ufeff" + encodeURIComponent(merged);
// 通过创建a标签实现
let link = document.createElement("a");
link.href = uri;
link.download = '测试.xlsx'; //这里是最后下载下来的excel表格名称
link.click();
}
// 怕数据中出现特殊字符和英文字符(会造成单元格分隔)的逗号所以这边过滤一下
function exportFormat(value){
value=value.replace(/[\n]/, '');
value=value.replace(/,/, ',');
return value;
}
好,上面代码的’/n’和’,’,’/n’是作用于在excel表中换行,’,‘是作用于在excel分隔单元格。这里我想吐个槽为什么其他人的博客都是’/t,’ 我自己试了一下/t并没有起到分隔单元格的作用,只有英文的逗号会起到分隔单元格的作用,中文的是不行的!
这里在记录一下自己在做这个导出时踩到的坑
1)因为一开始不知道英文字符的逗号会造成单元格分隔,然后自己的数据中还有这个英文的逗号所以导出的东西都是乱的,有个博客上写到**’\t’是用来分隔单元格用的,搞得我到后面找了很久才知道’,’**是用来分隔单元格的!
2)自己一开始没用join()去做把数组转换成字符串,用的toString()去做的转换字符串,因为toString()转换数组为字符串它会把数组中用于分隔的逗号也转换成字符串
所以导出来的东西就是乱的,在我一番测试下还是用了join()去转换字符串