node.jsxlsx

XLSX parsing results for January 1st of each year are different from other dates? Why?


Abnormal reproduction: https://github.com/dingdangdog/xlsx-1-1-test

Why does this problem occur and how can I solve it?


Solution

  • Finally, I still don’t know how to avoid the exception of data parsing on January 1st every year, so I can only handle it additionally. Here is a code example, I hope it can help you:

                // console.log(cellValue);
            if (typeof cellValue === "number" && cellValue > 0) {
              // The date in Excel starts from December 30, 1899
              const excelStartDate = new Date(1899, 11, 30);
              const resultDate = new Date(excelStartDate);
              resultDate.setDate(resultDate.getDate() + cellValue);
              // Add time zone offset (assuming +8 hours)
              resultDate.setHours(resultDate.getHours() + 8);
              // Simple date to string
              cellValue = resultDate.toISOString().split("T")[0];
              // Reassign the formatted string to sheetData, and the formatted data will be used for subsequent storage
              row[i] = cellValue;
            } else {
              // January 1st of each year is not a number after parsing, so no special processing is required, just treat it as a date
              // It is known that only Alipay will report an error on January 1st. I don't know the rest yet
              const resultDate = new Date(cellValue);
              // Add time zone offset (assuming it is +8 hours)
              resultDate.setHours(resultDate.getHours() + 8);
              cellValue = resultDate.toISOString().split("T")[0];
              // Reassign the formatted string to sheetData, and the formatted data will be used for subsequent storage
              row[i] = cellValue;
            }