gpt4 book ai didi

javascript - SheetJS:将行值从数组转置到对象

转载 作者:行者123 更新时间:2023-12-04 07:31:12 25 4
gpt4 key购买 nike

我正在尝试创建一个数组,其中每个“工作日”都是一个具有索引和开始/结束日期的对象,但我不知道如何操作 JSON 以具有特定结构。

我正在使用以下包:https://github.com/SheetJS/sheetjs

当前代码:

const workbook = XLSX.read(file.buffer, { type: 'buffer' });
const worksheet = workbook.Sheets['Calendar Config'];
const parsed = XLSX.utils.sheet_to_json(worksheet);

当前输出:

[
{
'Calendar Name': 'Standard',
'Valid From': 44197,
'Valid To': 44561,
'Use Holidays': 'yes',
'Working Day': 'Monday',
Start: 0.3333333333333333,
End: 0.8333333333333334
},
{
'Working Day': 'Tuesday',
Start: 0.3333333333333333,
End: 0.8333333333333334
},
{
'Working Day': 'Wednesday',
Start: 0.3333333333333333,
End: 0.8333333333333334
},
{
'Working Day': 'Thursday',
Start: 0.3333333333333333,
End: 0.8333333333333334
},
{
'Working Day': 'Friday',
Start: 0.3333333333333333,
End: 0.8333333333333334
},
{ 'Working Day': 'Saturday', Start: '-', End: '-' },
{ 'Working Day': 'Sunday', Start: '-', End: '-' }
]

所需的 JSON:

{
"name": "Standard",
"validFrom": "2021-01-01T00:00:00.000Z",
"validTo": "2021-12-31T00:00:00.000Z",
"useHolidays": true,
"workingDays": [
{
"dayIndex": 0,
"dayStart": "8:00",
"dayEnd": "20:00"
},
{
"dayIndex": 1,
"dayStart": "8:00",
"dayEnd": "20:00"
},
...
{
"dayIndex": 6,
"dayStart": "-",
"dayEnd": "-"
},
],
"uploadedBy": "foo"
}

已解析的 Excel 工作表:

excel screenshot

最佳答案

考虑一下,如果您的电子表格是这样的 - 解析每一行(并忽略标题)将使您能够更轻松地生成所需的输出:

1

您可以转置 sheet_to_json 输出来实现此目的。引用这个 issue 。注意 sheet_to_json 是用 {header: 1} 调用的:

const XLSX = require("xlsx");
const filename = "./Book1.xlsx";
const workbook = XLSX.readFile(filename);
const worksheet = workbook.Sheets["Calendar Config"];
const rowMajor = XLSX.utils.sheet_to_json(worksheet, {header: 1});

// transpose from row-major to column-major
// https://github.com/SheetJS/sheetjs/issues/1729
const rawTransposed = [];
for (let i=0; i<rowMajor.length; i++) {
for (let j=0; j<rowMajor[i].length; j++) {
if (!rawTransposed[j]) rawTransposed[j] = [];
rawTransposed[j][i] = rowMajor[i][j];
}
}

// clean out undefineds
const transposed = rawTransposed.map(arr => arr.filter(k => !!k));

console.log(transposed);

这会给你这个:

[
[ 'Calendar Name', 'Standard' ],
[ 'Valid From', 44197 ],
[ 'Valid To', 44561 ],
[ 'Use Holidays', 'yes' ],
[
'Working Day',
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday',
'Sunday'
],
[
'Start',
0.3333333333333333,
0.3333333333333333,
0.3333333333333333,
0.3333333333333333,
0.3333333333333333,
'-',
'-'
],
[
'End',
0.8333333333333334,
0.8333333333333334,
0.8333333333333334,
0.8333333333333334,
0.8333333333333334,
'-',
'-'
]
]

然后更直接地将此数组转换为所需的对象,例如您正在将 yes 转换为 true 并转换日期并混合工作日等。

const XLSX = require("xlsx");
const filename = "./Book1.xlsx";
const workbook = XLSX.readFile(filename);
const worksheet = workbook.Sheets["Calendar Config"];
const rowMajor = XLSX.utils.sheet_to_json(worksheet, {header: 1});

// transpose from row-major to column-major
// https://github.com/SheetJS/sheetjs/issues/1729
const rawTransposed = [];
for (let i=0; i<rowMajor.length; i++) {
for (let j=0; j<rowMajor[i].length; j++) {
if (!rawTransposed[j]) rawTransposed[j] = [];
rawTransposed[j][i] = rowMajor[i][j];
}
}

// clean out undefineds
const transposed = rawTransposed.map(arr => arr.filter(k => !!k));

// console.log(transposed);

// https://stackoverflow.com/questions/16229494/converting-excel-date-serial-number-to-date-using-javascript
function xlDateConvert(xlIndex) {
const d = new Date(Math.round(xlIndex - 25569) * 86400000);
return d.toISOString();
}

function xlTimeConvert(xlIndex, utcOffset) {
const hours = Math.floor((xlIndex % 1) * 24);
const minutes = Math.floor((((xlIndex % 1) * 24) - hours) * 60)
const d = new Date(Date.UTC(0, 0, xlIndex, hours - utcOffset, minutes));
return d.toLocaleTimeString("en-IT", {hour: "2-digit", minute:"2-digit", hour12: false});
}

// create custom object
const index = Array.from({length: 5}, (k, i) => i); // 5 keys in object
const output = index.reduce((acc, curr, idx) => {
switch (curr) {
case 0: // name
acc["name"] = transposed[idx].slice(1)[0];
break;
case 1: // validFrom
acc["validFrom"] = xlDateConvert(transposed[idx][1]);
break;
case 2: // validTo
acc["validTo"] = xlDateConvert(transposed[idx][1]);
break;
case 3: // useHolidays
acc["useHolidays"] = transposed[idx][1] === "yes" ? true : false;
break;
case 4: // workingDays
acc["workingDays"] = transposed[idx].slice(1).map((arr, i) => {
const start = transposed[idx + 1][i + 1];
const end = transposed[idx + 2][i + 1];
const dayStart = start === "-" ? start : xlTimeConvert(start, 10);
const dayEnd = end === "-" ? end : xlTimeConvert(end, 10);
return {
dayIndex: i,
dayStart: dayStart,
dayEnd: dayEnd
}
})
default:
break;
}
return acc;
}, {});

// some custom property
output["uploadedBy"] = "foo";

// output
console.log(output);

将输出:

{
name: 'Standard',
validFrom: '2021-01-01T00:00:00.000Z',
validTo: '2021-12-31T00:00:00.000Z',
useHolidays: true,
workingDays: [
{ dayIndex: 0, dayStart: '08:00', dayEnd: '20:00' },
{ dayIndex: 1, dayStart: '08:00', dayEnd: '20:00' },
{ dayIndex: 2, dayStart: '08:00', dayEnd: '20:00' },
{ dayIndex: 3, dayStart: '08:00', dayEnd: '20:00' },
{ dayIndex: 4, dayStart: '08:00', dayEnd: '20:00' },
{ dayIndex: 5, dayStart: '-', dayEnd: '-' },
{ dayIndex: 6, dayStart: '-', dayEnd: '-' }
],
uploadedBy: 'foo'
}

关于javascript - SheetJS:将行值从数组转置到对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67921536/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com