纯前端导出json为excel表格,不需要插件,直接上代码,导出函数:
/**
* @date 2019/3/21
* @author lxs
* @Description: 生成excel
* @param: titles:顶部一行名称集合{name:显示的名称,fieldName:对应json中的字段名} jsonData:所有数据json对象 worksheet:工作区名称,默认'Sheet' uri:uri类型默认excel
* @return: none
*/
function tableToExcel(titles,jsonData ,fileName = "下载", worksheet = 'Sheet',uri = 'data:application/vnd.ms-excel;base64,'){
let a = document.createElement('a')
//列标题
let str = '<tr>';
for (let i = 0; i < titles.length; i++) {
str += '<td>'+titles[i].name+'</td>'
}
str += '</tr>';
//循环遍历,每行加入tr标签,每个单元格加td标签
for(let i = 0 ; i < jsonData.length ; i++ ){
str+='<tr>';
for(let item of titles){
//增加\t为了不让表格显示科学计数法或者其他格式
str+= '<td>' + jsonData[i][item.fieldName] +'\t</td>';
}
str+='</tr>';
}
let 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>';
//下载模板
// window.location.href = uri + window.btoa(unescape(encodeURIComponent(template)));
a.setAttribute('href', uri + window.btoa(unescape(encodeURIComponent(template))));
a.download = fileName
a.click()
}
测试代码:
//测试代码
//要导出的json数据
const jsonData = [
{
name:'甲',
phone:'13112341111',
email:'13112341111@xx.com'
},
{
name:'乙',
phone:'13112341111',
email:'13112341111@xx.com'
},
{
name:'丙',
phone:'13112341111',
email:'13112341111@xx.com'
},
{
name:'丁',
phone:'13112341111',
email:'13112341111@xx.com'
},
]
const titles = [{name: '姓名',fieldName: 'name'},{name: '电话',fieldName: 'phone'},{name: '邮箱',fieldName: 'email'}];
tableToExcel(titles, jsonData,"导出名称");
感谢您的阅读!如果文章中有任何错误,或者您有更好的理解和建议,欢迎和我联系!