angular - 如何从角度的json文件中生成和下载excel表?
问题描述
我通过参考这个链接做了代码。但是出现错误
https://www.c-sharpcorner.com/article/excel-file-export-in-angular-using-service/
这是我的 JSON 文件
我在许多网站上搜索过,但找不到从 JSON 文件导出的 Excel 文件。任何人都可以帮助解决这个问题吗?
解决方案
**This the code for convert JSON to CSV file, Hope it will work for you**
DownloadJsonData(JSONData, FileTitle, ShowLabel) {
//If JSONData is not an object then JSON.parse will parse the JSON string in an Object
var arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData;
var CSV = '';
//This condition will generate the Label/Header
if (ShowLabel) {
var row = "";
//This loop will extract the label from 1st index of on array
for (var index in arrData[0]) {
//Now convert each value to string and comma-seprated
row += index + ',';
}
row = row.slice(0, -1);
//append Label row with line break
CSV += row + '\r\n';
}
//1st loop is to extract each row
for (var i = 0; i < arrData.length; i++) {
var row = "";
//2nd loop will extract each column and convert it in string comma-seprated
for (var index in arrData[i]) {
row += '"' + arrData[i][index] + '",';
}
row.slice(0, row.length - 1);
//add a line break after each row
CSV += row + '\r\n';
}
if (CSV == '') {
alert("Invalid data");
return;
}
//Generate a file name
var filename = FileTitle + (new Date());
var blob = new Blob([CSV], {
type: 'text/csv;charset=utf-8;'
});
if (navigator.msSaveBlob) { // IE 10+
navigator.msSaveBlob(blob, filename);
} 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.style = "visibility:hidden";
link.download = filename + ".csv";
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
}
}
推荐阅读
- python - 如何在 Django View 中仅存储所需的值
- django - 在 django 中将三个模型相乘并在视图中得到结果
- python - 如何在 Python 中对数据进行分组和求和并返回最大的和?
- c++ - 当我们尝试提取文件中的行,然后 istream::getline() 和 std::getline() 出现 `eof` 字符时,实际会发生什么
- python - fill_null() 值与其他列数据
- python - 遍历python中的字典值(.values()中的.keys()?)
- r - 层次结构中的崩溃因素
- python - Python 站点包从脚本根目录导入子模块
- c - 为什么二叉树的创建会出现问题?
- javascript - 无法根据来自另一个本地状态的值过滤掉 redux 状态