javascript 实现纯前端将数据导出excel两种方式

修改之前项目代码的时候,发现前人导出excel是用纯javascript实现的。并没有调用后台接口。

之前从来没这么用过,记录一下。以备不时之需。

方法一:

将table标签,包括tr、td等对json数据进行拼接,将table输出到表格上实现,这种方法的弊端在于输出的是伪excel,虽说生成xls为后缀的文件,但文件形式上还是html,代码如下:

<html>
<head>
    <p style="font-size: 20px;color: red;">使用table标签方式将json导出xls文件</p>
    <button onclick='tableToExcel()'>导出</button>
</head>
<body>
    <script> 
    const tableToExcel = () => {
        // 要导出的json数据
        const 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]'
            },
        ]
        // 列标题
        let str = '<tr><td>姓名</td><td>电话</td><td>邮箱</td></tr>';
        // 循环遍历,每行加入tr标签,每个单元格加td标签
        for(let i = 0 ; i < jsonData.length ; i++ ){
            str+='<tr>';
            for(const key in jsonData[i]){
                // 增加	为了不让表格显示科学计数法或者其他格式
                str+=`<td>${ jsonData[i][key] + ' '}</td>`;    
            }
            str+='</tr>';
        }
        // Worksheet名
        const worksheet = 'Sheet1'
        const uri = 'data:application/vnd.ms-excel;base64,';
 
        // 下载的表格模板数据
        const 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 + base64(template);
    };
 
    // 输出base64编码
    const base64 = s => window.btoa(unescape(encodeURIComponent(s)));
    </script>
</body>
</html>
复制代码

导出的文件后缀是xls,用office打开的时候不太友好。

然后,我发现了第二个方法

方法二

通过将json遍历进行字符串拼接,将字符串输出到csv文件,代码如下

<html>
<head>
    <p style="font-size: 20px;color: red;">使用a标签方式将json导出csv文件</p>
    <button onclick='tableToExcel()'>导出</button>
</head>
<body>
    <script>
    const tableToExcel = () => {
        // 要导出的json数据
        const jsonData = [
            {
                name:'路人甲',
                phone:'123456789',
                email:'[email protected]'
            },
            {
                name:'炮灰乙',
                phone:'123456789',
                email:'[email protected]'
            },
            {
                name:'土匪丙',
                phone:'123456789',
                email:'[email protected]'
            },
            {
                name:'流氓丁',
                phone:'123456789',
                email:'[email protected]'
            },
        ];
        // 列标题,逗号隔开,每一个逗号就是隔开一个单元格
        let str = `姓名,电话,邮箱
`;
        // 增加	为了不让表格显示科学计数法或者其他格式
        for(let i = 0 ; i < jsonData.length ; i++ ){
            for(const key in jsonData[i]){
                str+=`${jsonData[i][key] + '	'},`;    
            }
            str+='
';
        }
        // encodeURIComponent解决中文乱码
        const uri = 'data:text/csv;charset=utf-8,ufeff' + encodeURIComponent(str);
        // 通过创建a标签实现
        const link = document.createElement("a");
        link.href = uri;
        // 对下载的文件命名
        link.download =  "json数据表.csv";
        link.click();
    }
    </script>
</body>
</html>
复制代码

上边的两段代码复制即可用。

有好的建议,请在下方输入你的评论。

欢迎访问个人博客 guanchao.site

猜你喜欢

转载自juejin.im/post/7106291360260423716