xlsx-populate icon indicating copy to clipboard operation
xlsx-populate copied to clipboard

Question: How to determine a cell is of Date type?

Open Kukulkano opened this issue 4 years ago • 1 comments

Hi, I try to display some Excel content and found no way to determine if a cell is formatted as a date. My test documents are showing the date as formatted date in Excel but the xlsx-populate cell returns the numeric value only. I can calculate a date using XlsxPopulate.numberToDate() but how to find out if this number should be a date? I already use cell.formula() to determine that this cell contains a formula but how to determine if I have to display the number as date?

I already failed to check for Date object type (seems the type is simply int):

var myVal = myCell.value();
if (myVal instanceof Date) {
  // if date, but never jumps in here :-(
}

Any advice?

Kukulkano avatar Sep 13 '21 14:09 Kukulkano

This seems to work for me:

function isDate(cell): boolean {
    // https://foss.heptapod.net/openpyxl/openpyxl/-/blob/branch/3.1/openpyxl/styles/numbers.py
    let style = cell.style("numberFormat")

    if (typeof style !== 'string') {
        return false
    }

    const LITERAL_GROUP = /".*?"/g // anything in quotes
    const LOCALE_GROUP = /\[(?!hh?\]|mm?\]|ss?\])[^\]]*\]/g // anything in square brackets, except hours or minutes or seconds

    style = style.split(";")[0]
    style = style.replace(LITERAL_GROUP, "")
    style = style.replace(LOCALE_GROUP, "")
    return /(?<!\\)[dmhysDMHYS]/.test(style)
}

Linus789 avatar Feb 09 '23 12:02 Linus789