<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Title</title>
</head>
<body>
<script type="text/javascript">
/**
* 导出excel
* @param {Object} data 值列key-val
* @param {Object} fileName 文件名称
*/
function JSONToExcelConvertor(titleString, data, fileName) {
var CSV = '';
var row = "";
var arr=titleString.split(",");
var title=[];
for(var i = 0; i < arr.length; i++){
var d={};
d.title=arr[i].trim();
title.push(d);
}
for (var i = 0; i < title.length; i++) {
if(title[i].title){
row += title[i].title + ',';
}
}
row = row.slice(0, -1);
CSV += row + '\r\n';
for (var i = 0; i < data.length; i++) {
var row = "";
for (var j = 0; j < title.length; j++) {
if(title[j].title){
row += '"' + (data[i][title[j].title] ? data[i][title[j].title] : "") + '"\t,';
}
}
row.slice(0, row.length - 1);
CSV += row + '\r\n';
}
if (CSV == '') {
alert("Invalid data");
return;
}
var fileName = fileName;
var uri = new Blob(['\ufeff' + CSV], {type:"text/csv"});
var link = document.createElement("a");
link.href = URL.createObjectURL(uri);
link.style = "visibility:hidden";
link.download = fileName + ".csv";
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
function exportCvs() {
// id,name,age
var titleId = document.getElementById("titleId").value;
//[{"id":"111","name":"111","age":"10"}]
var dataId = document.getElementById("dataId").value;
JSONToExcelConvertor(titleId,eval('(' + dataId + ')'),"exportCvs");
}
</script>
<div>
样例:
<span style="color:red">title:</span>id,name,age
<span style="color:red">data:</span>[{"id":"111","name":"111","age":"10"}]
</div>
<div>
title:
<textarea rows="10" cols="60" id="titleId"></textarea>
data:
<textarea rows="10" cols="60" id="dataId"></textarea>
<button onclick="exportCvs()">导出CSV</button>
</div>
</body>
</html>
评论区