[英]Generate a csv file from a javascript array of objects
我知道這是一個已經回答的問題,但找不到適合我的解決方案。
我有一個 HTML 按鈕,單擊該按鈕時,會在打字稿(基本上是 javascript)中生成一組對象,我想生成一個將下載的 csv 文件。
這是 javascript 對象數組的示例:
var items = [
{ "name": "Item 1", "color": "Green", "size": "X-Large" },
{ "name": "Item 2", "color": "Green", "size": "X-Large" },
{ "name": "Item 3", "color": "Green", "size": "X-Large" }];
// Loop the array of objects
for(let row = 0; row < items.length; row++){
let keysAmount = Object.keys(items[row]).length
let keysCounter = 0
// If this is the first row, generate the headings
if(row === 0){
// Loop each property of the object
for(let key in items[row]){
// This is to not add a comma at the last cell
// The '\n' adds a new line
csv += key + (keysCounter+1 < keysAmount ? ',' : '\r\n' )
keysCounter++
}
}else{
for(let key in items[row]){
csv += items[row][key] + (keysCounter+1 < keysAmount ? ',' : '\r\n' )
keysCounter++
}
}
keysCounter = 0
}
console.log(csv)
var hiddenElement = document.createElement('a');
hiddenElement.href = 'data:text/csv;charset=utf-8,' + encodeURI(csv);
hiddenElement.target = '_blank';
hiddenElement.download = 'people.csv';
hiddenElement.click();
我嘗試了這個示例代碼,但在我的情況下,它創建了 csv 文件,但沒有在 csv 文件中正確插入 csv 字符串,csv 字符串具有由逗號分隔的元素行,每行由一個新行確定,但這里每一行的所有數據都位於 csv 文件的一個單元格中,我怎樣才能使每一行的每個值都位於不同的單元格中?
這是它的csv字符串:
name,color,size
Item 2,Green,X-Large
Item 3,Green,X-Large
CSV 只是一個文件,每個單元格用逗號分隔,每一行用新行分隔。 您想將每一列命名為對象的鍵。 如果我理解正確:
{ "name": "Item 1", "color": "Green", "size": "X-Large" }
將會:
---------------------------
| name | color | size |
---------------------------
| Item 1 | Green | X-Large |
---------------------------
更新:這是更新的版本。
因此,您可以使用 HTML5 中的 File API 循環數組並相應地生成 csv:
let csv
// Loop the array of objects
for(let row = 0; row < items.length; row++){
let keysAmount = Object.keys(items[row]).length
let keysCounter = 0
// If this is the first row, generate the headings
if(row === 0){
// Loop each property of the object
for(let key in items[row]){
// This is to not add a comma at the last cell
// The '\r\n' adds a new line
csv += key + (keysCounter+1 < keysAmount ? ',' : '\r\n' )
keysCounter++
}
}else{
for(let key in items[row]){
csv += items[row][key] + (keysCounter+1 < keysAmount ? ',' : '\r\n' )
keysCounter++
}
}
keysCounter = 0
}
// Once we are done looping, download the .csv by creating a link
let link = document.createElement('a')
link.id = 'download-csv'
link.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(csv));
link.setAttribute('download', 'yourfiletextgoeshere.csv');
document.body.appendChild(link)
document.querySelector('#download-csv').click()
順便說一句,如果您使用的是 TypeScript,那么最后一行document.querySelector('#download-csv').click()
必須是<HTMLElement>document.querySelector('#download-csv').click()
如果它對你有用。
用於 TypeScript 和 javascript(它只更改最后一行): https : //jsfiddle.net/0p8revuh/4/
更新:要查看在 excel 中正確格式化的文件,每個逗號分隔值的單元格,請執行以下操作:
它有效! 但是代碼的方式看起來更復雜,不容易理解。 我認為下面的代碼可能有點清楚。
另外,我通知我們需要正確保留對象鍵,例如,如果我們希望所有內容都在大寫中,我們需要將對象名稱保留在大寫中,但對象鍵的屬性我不喜歡大寫。 大多數時候它應該是小寫的。在這種情況下,這個解決方案也可能會有所幫助。
let csvText = '';
data.forEach((row, ind) => {
if (!ind) {
return (csvText += `${[
'STOCK',
'MAXPAIN',
'CASH RATE',
'FUTURE RATE',
'PE',
'PE OI',
'CE',
'CE OI',
'PC RATIO MAX',
'PC RATIO TOTAL'
].join(',')}\r\n`);
}
const properValues = [row.stock, row.option, row.strike, 0, row.put, row.put_oi, row.call, row.call_oi, 0, 0];
return (csvText += `${properValues.join(',')}\r\n`);
});
console.log(csvText);
確保標題值而不是標題值返回的順序相同; 否則,它會被石化。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.