js 實現純前端將資料匯出excel。chome瀏覽器 親測有效。
阿新 • • 發佈:2018-12-27
有了新的需求 所以就瞭解下怎麼用js 直接匯出excel文件。
html程式碼
<html lang="en">
<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>
<p style="font-size: 20px;color: red;">使用a標籤方式將json匯出csv檔案</p>
<button onclick="tableToExcel()">匯出</button>
</body>
</html>
標題js程式碼
<script>
window.onload = function(){
tableToExcel = function (){
//要匯出的json資料
var 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]'
},
];
//列標題,逗號隔開,每一個逗號就是隔開一個單元格
var str = "姓名,電話,郵箱\n";
//增加\t為了不讓表格顯示科學計數法或者其他格式
for(var i = 0 ; i < jsonData.length ; i++ ){
for(var item in jsonData[i]){
str+=jsonData[i][item]+"\t,";
}
str+='\n';
}
//encodeURIComponent解決中文亂碼
var 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>