1. 程式人生 > >原生javaScript匯出表格資料

原生javaScript匯出表格資料

<!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>