下载页面
<meta name="description" content="User login page" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0" />
<!--
导出功能,前端+ 后台功能。
http://localhost/Version10/Excel.html
-->
<!-- bootstrap & fontawesome -->
<link rel="stylesheet" href="assets/css/bootstrap.min.css" />
<link rel="stylesheet" href="assets/font-awesome/4.2.0/css/font-awesome.min.css" />
<!-- text fonts -->
<link rel="stylesheet" href="assets/fonts/fonts.googleapis.com.css" />
<!-- ace styles -->
<link rel="stylesheet" href="assets/css/ace.min.css" />
<!--[if lte IE 9]>
<link rel="stylesheet" href="assets/css/ace-part2.min.css" />
<![endif]-->
<link rel="stylesheet" href="assets/css/ace-rtl.min.css" />
<!--[if lte IE 9]>
<link rel="stylesheet" href="assets/css/ace-ie.min.css" />
<![endif]-->
<!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="assets/js/html5shiv.min.js"></script>
<script src="assets/js/respond.min.js"></script>
<![endif]-->
</head>
<body class="login-layout light-login">
<div style="background-color:red;">
<a href='#' onclick="tableToExcel()">测试按钮</a>
</div>
<table border="1">
<tr>
<td>row 1, cell 1</td>
<td>row 1, cell 2</td>
</tr>
<tr>
<td>row 2, cell 1</td>
<td>row 2, cell 2</td>
</tr>
</table>
</body>
function tableToExcel(){
//要导出的json数据
var jsonData = [
{
name:'路人甲',
phone:'123456789',
email:'000@123456.com',
number:22
},
{
name:'炮灰乙',
phone:'123456789',
email:'000@123456.com',
number:33
},
{
name:'土匪丙',
phone:'123456789',
email:'000@123456.com',
number:44
},
{
name:'流氓丁',
phone:'123456789',
email:'000@123456.com',
number:55
},
]
//列标题,逗号隔开,每一个逗号就是隔开一个单元格
let str = `姓名,电话,邮箱,数字\n`;
//增加\t为了不让表格显示科学计数法或者其他格式
for(let i = 0 ; i < jsonData.length ; i++ ){
for(let item in jsonData[i]){
//str+=`${jsonData[i][item] + '\t'},`;
str+=`${jsonData[i][item]},`;
}
str+='\n';
}
//encodeURIComponent解决中文乱码
let uri = 'data:text/csv;charset=utf-8,\ufeff' + encodeURIComponent(str);
//通过创建a标签实现
var link = document.createElement("a");
link.href = uri;
//对下载的文件命名
link.download = "json数据表.csv";
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
</script>
不正经的前端程序员
发布了90 篇原创文章 · 获赞 28 · 访问量 8万+
私信
关注