我正在尝试使用 exceljs 库将 JSON 数据导出到 csv/excel。我的数据有嵌套对象,我想将嵌套对象转换为列。
我有这个 JSON 数据
[
{
"name": "Raghav",
"grade": "I",
"marks": [
{
"subject": "Maths",
"grade": "A1"
},
{
"subject": "Science",
"marks": "B"
}
]
},
{
"name": "Isha",
"grade": "II",
"marks": [
{
"subject": "Maths",
"grade": "B1"
},
{
"subject": "Science",
"marks": "A"
}
]
}
]
这是将 JSON 数据导出到 csv 的代码
const ExcelJS = require('exceljs');
// excel export start
let workbook = new ExcelJS.Workbook()
let worksheet = workbook.addWorksheet('marks')
worksheet.columns = [
{ header: 'Name', key: 'name' },
{ header: 'Surname', key: 'surname' },
{ header: 'Marks', key: 'marks' },
]
worksheet.getRow(1).font = { bold: true }
async function exportToExcel() {
console.log('exportToExcel called');
let queryExport = query(collectionGroup(db, "2023-24"),
where('year', '==', '2023-24'),
where('section', '==', 'SSSV GSEB Primary (EM)'),
where('grade', '==', '8'),
where('division', '==', 'B'),
where('exam', '==', 'FA01'),
orderBy('roll', "asc"),
limit(2)
);
// getting data from Firestore
getDocs(queryExport)
.then((snapshot) => {
snapshot.forEach((doc, index) => {
const rowIndex = index + 2
let e = doc.data()
console.log(e);
let newEntry = doc.data();
newEntry.name = e.name;
newEntry.surname = e.surname;
worksheet.columns.forEach(column => {
worksheet.addRow({
...e,
})
})
});
workbook.xlsx.writeBuffer()
.then(buffer => FileSaver.saveAs(new Blob([buffer]), `pcs_bkp_${Date.now()}.xlsx`))
.catch(err => console.log('Error writing excel export', err))
});
}
上面的代码工作正常,我得到的 csv 文件如下所示。
但我想导出我的嵌套数组转换,预期结果应如下所示。
请帮我解决一下。
您的数据对象(不是 JSON 字符串,而是一个对象)包含奇怪格式的标记:对于主题“数学”,它们位于键“等级”下,对于“科学”,它们存储在“标记”下。
下面的代码片段可以处理它,但这只是演示 CSV 转换的初步尝试,因为一旦任何数据字符串中包含逗号,它就会中断。
const data=[{"name":"Raghav","grade":"I","marks":[{"subject":"Maths","grade":"A1"},{"subject":"Science","marks":"B"}]},{"name":"Isha","grade":"II","marks":[{"subject":"Maths","grade":"B1"},{"subject":"Science","marks":"A"}]}];
const csv=["Name","Grade",data[0].marks.map(m=>m.subject)].join(",")+"\n"
+data.map((d,i)=>[d.name,d.grade,...d.marks.map(m=>m.grade||m.marks)].join(",")
).join("\n");
console.log(csv);