我正在尝试将以下 JSON 转换为 excel,我正在使用 XLSX 对于它,它正在将我的 JSON 转换为 excel,但是,dailyPointsArray 的嵌套数组在转换为 excel 后是空白的。
试过代码
const XLSX = require("xlsx");
const workSheet = XLSX.utils.json_to_sheet(attendanceData);
const workBook = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(workBook, workSheet, "attendance");
XLSX.write(workBook, { bookType: "xlsx", type: "buffer" });
XLSX.write(workBook, { bookType: "xlsx", type: "binary" });
XLSX.writeFile(workBook,"newExcel.xlsx");
attendanceData:[
{
workerId: '1230',
workerFullName: 'A',
workerDepartment: 'INFORMATION TECHNOLOGY',
workerDesignation: 'ASSISTANT MANAGER',
Location: 'locationA',
dailyPointsArray: [
{
inTime: '-',
Date: '23/03/2022',
outTime: '-',
Points: null,
createdAs: 'ABSENT'
},
{
inTime: '-',
Date: '24/03/2022',
outTime: '-',
Points: null,
createdAs: 'ABSENT'
}
],
total_duration: 0,
total_shift_points: 0
},
{
workerId: '1128',
workerFullName: 'B',
workerDepartment: 'INFORMATION TECHNOLOGY',
workerDesignation: 'MANAGER',
Location: 'LocationA',
dailyPointsArray: [
{
inTime: '-',
Date: '23/03/2022',
outTime: '-',
Points: null,
createdAs: 'ABSENT'
},
{
inTime: '-',
Date: '24/03/2022',
outTime: '-',
Points: null,
createdAs: 'ABSENT'
}
],
total_duration: 17,
total_shift_points: 2
},
]
下面是excel文件输出如您所见,dailyPointsArray 的列是空的。
我想我的 excel 文件应该像下图
最佳答案
尝试展平数组:过滤嵌套数组,按您想要的顺序获取您想要的键
尝试这个:
const filtered = attendanceData.map(obj => {
// get totals to add them later to keep column order (or use `header` param for columns order)
const {
dailyPointsArray,
total_duration,
total_shift_points,
...rest
} = obj;
// flatten..
dailyPointsArray.map(el => {
rest[el['Date']] = el.createdAs;
});
return {...rest,
total_duration,
total_shift_points
};
});
const XLSX = require("xlsx");
const workSheet = XLSX.utils.json_to_sheet(filtered);
const workBook = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(workBook, workSheet, "attendance");
XLSX.write(workBook, { bookType: "xlsx", type: "buffer" });
XLSX.write(workBook, { bookType: "xlsx", type: "binary" });
XLSX.writeFile(workBook,"newExcel.xlsx");
关于javascript - 如何在nodejs中将嵌套的JSON转换为excel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71618049/