原生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:'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 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>

 

posted @ 2018-11-16 18:01  付正义  阅读(658)  评论(0编辑  收藏  举报