node-csv-stringify icon indicating copy to clipboard operation
node-csv-stringify copied to clipboard

Fields starting with equals (`=`) do not open correctly in Excel

Open kiprobinson opened this issue 6 years ago • 7 comments

If a field value starts with equals character (=), the csv does not open correctly in Excel. This may technically be an Excel problem, but it would be nice if there was some kind of "excelSafe" option to csv-stringify.

Examples:

Field       CSV Encoding     What Excel Shows      Excel-safe CSV Encoding (causes Excel to show same as input)
=test       =test            #NAME?                "=""=test"""
="test"     "=""test"""      test                  "=""=""""test"""""""
="test      "=""test"        ="test                "=""=""""test"""

Workaround:

cast: {
    string: s => s.charAt(0) === '=' ? `="${s.replace(/"/g,'""')}"` : s,
}

kiprobinson avatar Nov 20 '19 18:11 kiprobinson

Update: I found a related issue that references this page which suggests this is a problem if a field starts with =, +, -, or @. That page also says simply putting a ' in front of the cell value works, but in my testing on latest version of Excel that's not true.

So my updated workaround would be:

cast: {
    string: s => s.match(/^[=+\-@]/) ? `="${s.replace(/"/g,'""')}"` : s,
}

kiprobinson avatar Nov 20 '19 19:11 kiprobinson

In your exemple above, you could delegate the escape work to the library:

cast: {
    string: s => {value: s, quoted: s.match(/^[=+\-@]/) },
}

wdavidw avatar Nov 20 '19 20:11 wdavidw

This being said, we could introduce a new option, safe_spreadsheet or anything else if the usecase is shared among several user. Any suggestion for the name of the option ?

wdavidw avatar Nov 20 '19 20:11 wdavidw

Just quoting is not enough. "=test" still gives #NAME? when opened in excel. from my testing, it has to be ="=test".

I think Excel first takes the value and parses, i.e. if it's quoted it unquotes, otherwise it takes the original value. Then it says "ok does this start with an equals sign? if so it's a formula let me evaluate it".

I'm not sure what happens if you try to open in Google spreadsheets--it may just be an Excel problem in which case I'd suggest calling it "excelSafe".

kiprobinson avatar Nov 20 '19 21:11 kiprobinson

I don't have excell on my host but with libreoffice, "=test" is broken as well and ="=test" is a correct solution.

wdavidw avatar Nov 20 '19 23:11 wdavidw

PapaParse has this option as escapeFormulae Added on https://github.com/mholt/PapaParse/pull/796

(Also related to https://github.com/adaltas/node-csv-stringify/issues/69)

tomyam1 avatar Dec 09 '20 07:12 tomyam1

Is someone interested in proposing a pull request ?

wdavidw avatar Dec 09 '20 08:12 wdavidw