根据 ui-grid 的每行 id 在 AngularJs 中将 JSON 数据导出到 CSV 文件
我需要在 angularjs 1.0 UI-grid 的每一行中有一个 CSV 导出选项,用户将单击该按钮,并且根据 id 服务器将响应基于 JSON 的数据,然后它应该以 CSV 格式下载。
请参阅下图,其中包含导出 CSV 按钮。
这是我迄今为止尝试过的:
网格的列定义
{
field: "actions", "name": "Action",
cellTemplate: '<button type="button" field-separator="," ng-click="funcExport({{row.entity._id}})" csv-header="exportHeader" ng-csv="export" filename="Sample.csv">Export CSV</button>',
width: "170"
}
导出函数到CSV:目前JSON数据不是基于id而是静态的用于演示。
/*Function to export*/
var funcExport = function (id) {
$scope.exportarray = [];
$scope.exportHeader = [];
$scope.export = [];
$scope.exportHeader = ['Licence', 'Condition'];
$scope.exportarray = [{ "Licence": "229973", "Condition": "Usage" }, { "Licence": "24141", "Condition": "Level" }];
$scope.export = $scope.exportarray;
}
如有任何帮助,我们将不胜感激!!
最佳答案
首先将 JSON 转换为逗号分隔的 CSV 字符串,然后创建一个 anchor 标记(a) 将此 CSV 字符串设置为 href
触发点击,删除 anchor 标记。
function convertToCSV(array) {
var str = '';
for (var i = 0; i < array.length; i++) {
var line = '';
for (var index in array[i]) {
if (line != '') line += ','
line += array[i][index];
}
str += line + '\r\n';
}
return str;
}
function exportCSVFile(headers, items, fileTitle) {
items.unshift(headers);
var csv = convertToCSV(items);
var exportedFilenmae = fileTitle + '.csv' || 'export.csv';
var blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
if (navigator.msSaveBlob) { // IE 10+
navigator.msSaveBlob(blob, exportedFilenmae);
} else {
var link = document.createElement("a");
if (link.download !== undefined) { // feature detection
// Browsers that support HTML5 download attribute
var url = URL.createObjectURL(blob);
link.setAttribute("href", url);
link.setAttribute("download", exportedFilenmae);
link.style.visibility = 'hidden';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
}
}
/*Function to export*/
var funcExport = function (id) {
var exportHeader = ['Licence', 'Condition'];
var exportarray = [{ "Licence": "229973", "Condition": "Usage" }, { "Licence": "24141", "Condition": "Level" }];
exportCSVFile(exportHeader , exportarray, 'download' );
}
此代码取自 here
关于javascript - 根据ui-grid的每行id将JSON数据导出到AngularJs中的CSV文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61569863/