我正在向此函数传递一个文件,我想将数据转换为 json,但对于特定列 DOB 05-04-2001 转换为随机数,例如 36986。我想要输入作为此函数响应的确切日期,如何去做这个 ?谁能帮帮我吗?
static convertExcelFileToJsonUsingXlsxTrimSpaces = (path: string) => {
// Read the file using pathname
const file = xlsx.readFile(path);
// Grab the sheet info from the file
const sheetNames = file.SheetNames;
const totalSheets = sheetNames.length;
// Variable to store our data
const parsedData: any[] = [];
// Loop through sheets
for (let i = 0; i < totalSheets; i += 1) {
// Convert to json using xlsx
const sheetData = xlsx.utils.sheet_to_json(file.Sheets[sheetNames[i]], { raw: true });
console.log(sheetData);
// Process each row to handle tab-separated values
const processedData: any[] = [];
sheetData.forEach((row: any) => {
const processedRow: any = {};
Object.keys(row).forEach((key) => {
processedRow[key] = row[key].toString().trim(); // Convert to string and trim whitespace
});
processedData.push(processedRow);
});
// Add the sheet's processed data to our data array
parsedData.push(...processedData);
}
return parsedData;
};
这不是随机数,而是日期单元格的默认解析。
要获取日期值,请在解析选项中添加
cellDates: true
标志:
试试这个:
const sheetData = xlsx.utils.sheet_to_json(file.Sheets[sheetNames[i]], { raw: true, cellDates: true });
请参阅文档:
默认情况下,Excel 将日期存储为数字,其格式代码为 指定日期处理。例如,存储日期 2017 年 2 月 19 日 如数字 42785,数字格式为 d-mmm-yy
所有解析器的默认行为是生成数字单元格。 将 cellDates 设置为 true 将强制生成器存储日期。