var str = "\uFEFF"+JSON2CSV(jsonobj);
var dataUri = 'data:text/csv;charset=utf-8,' + encodeURIComponent(str);
var link = document.getElementById('link').href = dataUri;
<a href="#" id="link" download="download.csv">下載</a>
function JSON2CSV(objArray) {
var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
var str = '';
var line = '';
//if ($("#labels").is(':checked')) {
var head = array[0];
if ($("#quote").is(':checked')) {
for (var index in array[0]) {
var value = index + "";
line += '"' + value.replace(/"/g, '""') + '",';
}
} else {
for (var index in array[0]) {
line += index + ',';
}
}
line = line.slice(0, -1);
str += line + '\r\n';
//}
for (var i = 0; i < array.length; i++) {
var line = '';
if ($("#quote").is(':checked')) {
for (var index in array[i]) {
var value = array[i][index] + "";
line += '"' + value.replace(/"/g, '""') + '",';
}
} else {
for (var index in array[i]) {
if (typeof array[i][index] == 'object' && array[i][index] != null) {
line += "\"";
for (var j = 0; j < array[i][index].length; j++) line += array[i][index][j] + '\n';
line += "\",";
}
else line += array[i][index] + ',';
}
}
line = line.slice(0, -1);
str += line + '\r\n';
}
return str;
}
動態產生HTML 元件達到下載效果
function downloadURI(uri, name) {
var link = document.createElement("a");
link.download = name;
link.href = uri;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
delete link;
}
沒有留言:
張貼留言