EasyUI-导出Datagrid数据到csv

时间:2022-04-10 23:16:12
function ExportToXls(gridName,csvName){
var data = JSON.stringify($("#"+gridName).datagrid('getData').rows);
//alert(data);
if (data == '')
return;

JSONToCSVConvertor(data, csvName, true);
}
function JSONToCSVConvertor(JSONData, ReportTitle, ShowLabel) {
//如果JSONData 不是json对象,就把JSONData 转换为json对象
var arrData = typeof JSONData != 'object' ? JSON.parse(JSONData): JSONData;

var CSV = '';
CSV += ReportTitle + '\r\n\n';
if (ShowLabel) {
var row = "";
for ( var index in arrData[0]) {
row += index + ',';
}
row = row.slice(0, -1);
CSV += row + '\r\n';
}
for (var i = 0; i < arrData.length; i++) {
var row = "";
for ( var index in arrData[i]) {
row += '"' + arrData[i][index] + '",';
}
row.slice(0, row.length - 1);
CSV += row + '\r\n';
}

if (CSV == '') {
alert("Invalid data");
return;
}

//文件名
var fileName = "MyReport_";
fileName += ReportTitle.replace(/ /g, "_");

var uri = 'data:text/csv;charset=utf-8,' + escape(CSV);


var link = document.createElement("a");
link.href = uri;


link.style = "visibility:hidden";
link.download = fileName + ".csv";


document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}