天天看点

jQuery导出xls源码(简单容易理解)

用户需求: 将一些指定数据进行导出;

(注意:该方法当数据量过大是会使浏览器崩溃,建议小数据量使用)

话不多说,直接上码:

<!DOCTYPE html>
<html >
<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>xls导出</title>
    <link rel="stylesheet" href="layui/css/layui.css" target="_blank" rel="external nofollow"   media="all">
    <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>             
</head>

<body>
      <button onclick="xls();" style="margin:0px 500px">导出按钮</button>
</body>
<script>
function xls(){
    let list = [{PlayerId:"小宝"},{PlayerId:888888},{PlayerId:"小er"},{PlayerId:7777}];
    let str = `序号,用户ID\n`;
    //增加\t为了不让表格显示科学计数法或者其他格式
    for(let i = 0 ; i < list.length ; i++ ){
        let PlayerId = list[i]["PlayerId"];
        let index = i+1;
        str+=`${index + '\t'},`+`${PlayerId + '\t'},` +'\n';
    }
    //encodeURIComponent解决中文乱码
    let uri = 'data:text/xls;charset=utf-8,\ufeff' + encodeURIComponent(str);
    //通过创建a标签实现
    var link = document.createElement("a");
    link.href = uri;
    //对下载的文件命名
    link.download =  "韦大宝统计.xls";
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}
</script>
</html>