csvCell.ts 824 B

123456789101112131415161718
  1. // A cell starting with one of these is read as a formula by spreadsheet apps,
  2. // including the full-width forms some normalise to ASCII.
  3. const FORMULA_PREFIXES = ['=', '+', '-', '@', '=', '+', '-', '@'];
  4. /**
  5. * One CSV cell, quoted. Text that starts like a formula gets a leading quote
  6. * so a spreadsheet shows it as typed; leading whitespace is looked past, and
  7. * a value starting with a tab or line break is quoted too. Numbers are
  8. * written as they are.
  9. */
  10. export function csvCell(value: unknown): string {
  11. let text = String(value ?? '');
  12. if (typeof value === 'string' && text !== '') {
  13. const startsLikeFormula = FORMULA_PREFIXES.some((p) => text.trimStart().startsWith(p));
  14. if ('\t\r\n'.includes(text[0]) || startsLikeFormula) text = `'${text}`;
  15. }
  16. return `"${text.replace(/"/g, '""')}"`;
  17. }