Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

[BUG] Csv reading - cells filled with spaces only are converted to 0 #2751

Open
tlgman opened this issue Apr 23, 2024 · 0 comments 路 May be fixed by #2752
Open

[BUG] Csv reading - cells filled with spaces only are converted to 0 #2751

tlgman opened this issue Apr 23, 2024 · 0 comments 路 May be fixed by #2752

Comments

@tlgman
Copy link

tlgman commented Apr 23, 2024

馃悰 Bug Report

When I pass a csv with a cell containing only spaces, it is converted to 0 by csv.read.

Lib version: 4.4.0

Steps To Reproduce

const wb = new ExcelJS.Workbook();
wb.csv.read(Stream.Readable.from('firstValue;    ;secondValue', { parserOptions: { delimiter: ';' } })
const ws = wb.worksheets[templateInfo.worksheet];

const row1 = ws.getRow(1);
const cell12 = row1.getCell(2);
console.log('cell: 1,2: ', cell12.value); // 0 => Expected string : '    '

The expected behaviour:

Cell 1,2 is not a number, and should be converted to a string, not a number.

Possible solution (optional, but very helpful):

The problem comes from default mapper in the csv parser. It check whether datum could be a number with Number(datum).
But Number(' ') returns a number. I think is not the expected case for this conversion.

// csv.js
 function(datum) {
    if (datum === '') {
      return null;
    }
    const datumNumber = Number(datum); // -------> Here !!!
    if (!Number.isNaN(datumNumber) && datumNumber !== Infinity) {
      return datumNumber;
    }
    const dt = dateFormats.reduce((matchingDate, currentDateFormat) => {
      if (matchingDate) {
        return matchingDate;
      }
      const dayjsObj = dayjs(datum, currentDateFormat, true);
      if (dayjsObj.isValid()) {
        return dayjsObj;
      }
      return null;
    }, null);
    if (dt) {
      return new Date(dt.valueOf());
    }
    const special = SpecialValues[datum];
    if (special !== undefined) {
      return special;
    }
    return datum;
  };

The solution could be trim data before passing it to Number function.

Possible hack while it's not merged

It's to pass our own fixed mapper :

wb.csv.read(Stream.Readable.from(myCsv, { map: myOwnMapper, parserOptions: { delimiter: ';' } })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant