1

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");
  }

Excel column: enter image description here

Output: enter image description here

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 :((

2
  • So your problem is white color of print (Wrong as string), purple color of print(correct as Data/time) so you want to white color of print as handling as same as purple rows? Commented Mar 4, 2024 at 22:42
  • 1
    Looks like Excel will not accept dates before 1900, for example this and this. Also, note that there was an Excel bug that treated 1900 as a leap year, there are some threads about it, for example: this. Commented Mar 5, 2024 at 2:04

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.