I'm encountering an issue while parsing an Excel file using ExcelJS in a Node.js environment. The Excel file contains cells representing dates, but it seems that some of these cells are being treated as strings, while others are correctly converted to actual date objects. Despite trying various approaches, I haven't been able to resolve this issue.
Below is a snippet of my code:
export default async (req: Request, res: Response) => {
const workbook = new ExcelJS.Workbook();
if (!req.files?.length) {
res.send("Files not found");
return;
}
try {
// @ts-ignore
await workbook.xlsx.load(req.files[0].buffer);
const worksheet = workbook.getWorksheet(1);
if (worksheet?.actualColumnCount != EXCEL_COLUMN_NUMBER) {
return res.status(400).send({
user_message:
"Not correct number of column",
});
}
worksheet.spliceRows(1, 1);
worksheet?.eachRow(async (row, rowIndex) => {
const rowCellValue = row.values as CellValue[]
console.log("Birthdate :", rowCellValue[ExcelColumns.BirthDate];
});
} catch (error) {
console.error("Error processing Excel file:", error);
res.status(500).send("Error processing Excel file");
}
I desire to ensure that all cells in the Excel file have a unique type (either text or date) so that I can parse them accurately. While I acknowledge that checking the type is a viable solution, I am reluctant to accept it as the sole approach.
I attempted to address this issue by creating a parsing function, but it fails due to the incorrect expected type:
export function parseStringToDate(dateString: string): Date | null {
const formats = [
{ format: "DD/MM/YYYY", separator: "/" },
{ format: "MM/YYYY", separator: "/" },
{ format: "YYYY", separator: "/" },
];
for (const { format, separator } of formats) {
const tokens = format.split("/");
const dateParts = dateString.split(separator);
if (dateParts.length === tokens.length) {
const dateValues: any = {};
for (let i = 0; i < tokens.length; i++) {
const token = tokens[i];
const part = dateParts[i];
if (!isNaN(parseInt(part, 10))) {
dateValues[token] = parseInt(part, 10);
} else {
return null;
}
}
const year = dateValues["YYYY"];
const month = dateValues["MM"] || 1;
const day = dateValues["DD"] || 1;
if (month < 1 || month > 12 || day < 1 || day > 31) {
return null;
}
return new Date(year, month - 1, day);
}
}
return null;
}
Please help :((

