javascript - Js数组到CSV添加列标题
问题描述
这是CSV
从数组生成的代码,硬编码值给出了正确的列标题和行中的数据。我正在使用循环添加数据,但无法理解如何添加列标题。
这是导出 csv 的硬编码数组
var Results = [
["Col1", "Col2", "Col3", "Col4"],
["Data", 50, 100, 500],
["Data", -100, 20, 100],
];
exportToCsv = function() {
var CsvString = "";
Results.forEach(function(RowItem, RowIndex) {
RowItem.forEach(function(ColItem, ColIndex) {
CsvString += ColItem + ',';
});
CsvString += "\r\n";
});
CsvString = "data:application/csv," + encodeURIComponent(CsvString);
var x = document.createElement("A");
x.setAttribute("href", CsvString );
x.setAttribute("download","somedata.csv");
document.body.appendChild(x);
x.click();
}
<button onclick="exportToCsv()">export to CSV</button>
当我使用这样的循环插入行值时,如何管理col1 、 col2 、 col3 -
for(let i=0;i<this.goalList.length;i++)
{
console.log(i,this.goalList)
var Result = [
[this.goalList[i]['name'],this.goalList[i]['desc'], this.goalList[i]['phno']]
];
Results.push(Result);
}
解决方案
如果您有标题 Col1,Col2,Col3;
function downloadCsv(){
var rows= [{'col1':10,'col2':10,'col3':10},{'col1':10,'col2':10,'col3':10},
{'col1':10,'col2':10,'col3':10},{'col1':10,'col2':10,'col3':10}]
var headers = "col1,col2,col3\n";
rows.forEach((row)=>{
var values = []
Object.keys(row).forEach((key)=>{
if(Array.isArray(row[key])){
var type = [];
row[key].forEach(element => {
type.push(element.name)
});
console.log(type)
values.push("\"" + type.join() + "\"")
}else{
typeof(row[key]) == "string" ? values.push("\"" + row[key] + "\"") : (row[key] == null ? values.push("") : values.push(row[key].toString()))
}
});
headers = headers + values.join(",") + "\n"
})
download('CSV', 'Payroll.csv', 'text/csv', headers)
}
如您所见,我们必须知道 JSON 的“键”是什么,为了动态创建它们,我们获取对象的键并循环它们,并创建我们想要的 csv 格式。
工作 JsFiddle https://jsfiddle.net/36o8cryu/
推荐阅读
- git - 如何从 git 对象中读取文件内容?
- c# - ISO8583 带 unicode 字符的字段长度
- regex - Is there a way to get the beginning of a word based on the match of the end of the word?
- c# - How to fix "Couldn't assign value into ICollection property"
- r - 如何返回每组的最后一个匹配条件行?
- sql - Can I hard code a value into column in the SELECT clause
- java - How to record context in logs when task is run by multiple thread
- c++ - C ++如何将参数绑定到接受函数的函数?
- sql-server - T-SQL SELECT * 快,SELECT TOP 50 慢
- android - Devices disconnecting during application installation through Android studio using new MACBOOK