原生javaScript導出表格數據
阿新 • • 發佈:2018-11-16
email csv 表格 cli onclick solid nload UNC ont
<!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <title>Document</title> </head> <body> <button onclick="exportData(header,jsonData,‘solid‘,‘csv‘)">導出csv</button> <button onclick="exportData(header,[],‘下載模板‘,‘csv‘)">下載模板</button> </body> </html> <script type="text/javascript"> //表頭 var header = [ { key: ‘name‘, value: ‘姓名‘ }, { key: ‘email‘, value: ‘郵箱‘ }, { key: ‘age‘, value: ‘年齡‘ }, { key: ‘phone‘, value: ‘手機號‘ }, { key:‘address‘, value: ‘地址‘ } ] //表格數據 var jsonData = [ { name:‘孫悟空‘, phone:‘123456‘, email:‘[email protected]‘ }, { name:‘豬八戒‘, phone:‘123456‘, email:‘[email protected]‘ }, { name:‘沙和尚‘, phone:‘123456‘, email:‘[email protected]‘ }, { name:‘唐僧‘, phone:‘123456‘, email:‘[email protected]‘ } ] function exportData(header, jsonData, fileName,extension){ //列標題,用逗號隔開,每一個逗號就是隔開一個單元格 let str = ‘‘; var keys = []; for(i = 0; i<header.length; i++){ str+=`${header[i].value}\t,`; keys.push(header[i].key); } str +=`\n` for(let i = 0; i<jsonData.length; i++){ for(let j = 0; j < keys.length; j++){ console.log(jsonData[i],keys[j]) str+=`${jsonData[i][keys[j]] || ‘‘}\t,` } str+=`\n` } let uri = ‘data:text/csv;charset=utf-8,\ufeff‘ + encodeURIComponent(str); download(uri,fileName,extension); } function download(url,fileName,extension){ var oA = document.createElement(‘a‘); oA.href = url; oA.download = `${fileName}.${extension}`; document.body.appendChild(oA); oA.click(); document.body.removeChild(oA); } </script>
原生javaScript導出表格數據