js导出数据到excel

方式一

var jsonData = [
{
name:'路人甲',
phone:'123456',
email:'123@123456.com'
},
{
name:'炮灰乙',
phone:'123456',
email:'123@123456.com'
},
{
name:'土匪丙',
phone:'123456',
email:'123@123456.com'
},
{
name:'流氓丁',
phone:'123456',
email:'123@123456.com'
},
]

function JSONToCSVConvertor(JSONData, ReportTitle, ShowLabel) {
//If JSONData is not an object then JSON.parse will parse the JSON string in an Object
var arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData;

var CSV = '';
//Set Report title in first row or line

CSV += '姓名,电话,邮箱 ';

//This condition will generate the Label/Header
// if (ShowLabel) {
// var row = "";
//
// //This loop will extract the label from 1st index of on array
// for (var index in arrData[0]) {
//
// //Now convert each value to string and comma-seprated
// row += index + ',';
// }
//
// row = row.slice(0, -1);
//
// //append Label row with line break
// CSV += row + ' ';
// }

//1st loop is to extract each row
for (var i = 0; i < arrData.length; i++) {
var row = "";

//2nd loop will extract each column and convert it in string comma-seprated
for (var index in arrData[i]) {
row += '"' + arrData[i][index] + '",';
}

row.slice(0, row.length - 1);

//add a line break after each row
CSV += row + ' ';
}

if (CSV == '') {
alert("Invalid data");
return;
}

//Generate a file name
var fileName = "MyReport_";
//this will remove the blank-spaces from the title and replace it with an underscore
fileName += ReportTitle.replace(/ /g,"_");

//Initialize file format you want csv or xls
CSV = encodeURIComponent(CSV);
var uri = 'data:text/csv;charset=utf-8,ufeff' + CSV;

// Now the little tricky part.
// you can use either>> window.open(uri);
// but this will not work in some browsers
// or you will not get the correct file extension

//this trick will generate a temp <a /> tag
var link = document.createElement("a");
link.href = uri;

//set the visibility hidden so it will not effect on your web-layout
link.style = "visibility:hidden";
link.download = fileName + ".csv";

//this part will append the anchor tag and remove it after automatic click
document.body.appendChild(link);
link.click();
document.body.removeChild(link);

方式二:

function TableToExcel(){
//要导出的json数据
var jsonData = [
{
name:'001',
id:'621699190001011231'
},
{
name:'002',
id:'52069919000101547X'
},
{
name:'003',
id:'423699190103015469'
},
{
name:'004',
id:'341655190105011749'
}
]
//导出前要将json转成table格式
//列标题
var str = '<tr><td>name</td><td>id</td></tr>';
//具体数值 遍历
for(let i = 0;i < jsonData.length;i++){
str += '<tr>';
for(let item in jsonData[i]){
var cellvalue = jsonData[i][item];
//不让表格显示科学计数法或者其他格式
//方法1 tr里面加 style="mso-number-format:'@';" 方法2 是改为 = 'XXXX'格式
//如果纯数字且超过15位
/*var reg = /^[0-9]+.?[0-9]*$/;
if ((cellvalue.length>15) && (reg.test(cellvalue))){
//cellvalue = '="' + cellvalue + '"';
}*/
//此处用`取代',具体用法搜索模板字符串 ES6特性
str+=`<td style="mso-number-format:'@';">${cellvalue}</td>`;
// str+=`<td>${cellvalue}</td>`;
}
str+='</tr>';
}
var worksheet = '导出结果'
var uri = 'data:application/vnd.ms-excel;base64,';
//下载的表格模板数据
var 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><!--[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>${str}</table></body></html>`;
//下载模板
function base64 (s) { return window.btoa(unescape(encodeURIComponent(s)))}
window.location.href = uri + base64(template);
}

原文地址:https://www.cnblogs.com/hongyumao/p/14271650.html