xls-reader 0.7.4 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,17 @@
1
1
  # xls-reader
2
2
 
3
+ ## 0.9.0
4
+
5
+ ### Minor Changes
6
+
7
+ - [#71](https://github.com/zanlucathiago/xls-reader/pull/71) [`0ec0d11`](https://github.com/zanlucathiago/xls-reader/commit/0ec0d11b9360c20bd05aee7a2ceaa0963b440576) Thanks [@zanlucathiago](https://github.com/zanlucathiago)! - `sheetToObjects` gains two opt-in options. `skipBlankRows: true` drops rows whose cells are all `null` or whitespace-only text. `duplicateHeaders: "suffix"` keeps every column when a header repeats, renaming the repeats `Id_2`, `Id_3`, … instead of letting the rightmost column overwrite the others. Defaults are unchanged.
8
+
9
+ ## 0.8.0
10
+
11
+ ### Minor Changes
12
+
13
+ - [#69](https://github.com/zanlucathiago/xls-reader/pull/69) [`7aa4e3c`](https://github.com/zanlucathiago/xls-reader/commit/7aa4e3c25f1623e2866915ef453fe2a87853b7fb) Thanks [@zanlucathiago](https://github.com/zanlucathiago)! - Export `cellToString(cell, { dateFormat })`, the per-cell text rendering that `sheetToCsv` already used, so importers that build their own rows don't have to reimplement it. `dateFormat: "compact"` writes a midnight date as `2024-04-02` and drops milliseconds otherwise; `sheetToCsv` accepts the same option. The default (`"iso"`) keeps today's output.
14
+
3
15
  ## 0.7.4
4
16
 
5
17
  ### Patch Changes
package/README.md CHANGED
@@ -157,17 +157,27 @@ Parses a whole workbook. Throws `XlsError` if the bytes aren't a BIFF `.xls`.
157
157
 
158
158
  The first worksheet, for the single-sheet case.
159
159
 
160
- ### `sheetToObjects(sheet: Sheet, options?: { headerRow?: number }): RowObject[]`
160
+ ### `sheetToObjects(sheet: Sheet, options?: SheetToObjectsOptions): RowObject[]`
161
161
 
162
162
  Turns a sheet's rows into objects keyed by a header row (the first by default).
163
163
  Blank-header columns are skipped and short rows are padded with `null`.
164
164
 
165
- ### `sheetToCsv(sheet: Sheet, options?: { delimiter?: string; eol?: string }): string`
165
+ | Option | Default | What it does |
166
+ | ------------------ | ------------- | ---------------------------------------------------------------------------------------------------------- |
167
+ | `headerRow` | `0` | 0-based row that holds the keys; rows above it are ignored. |
168
+ | `skipBlankRows` | `false` | Drops rows where every cell is `null` or whitespace-only text. |
169
+ | `duplicateHeaders` | `"overwrite"` | `"overwrite"`: a repeated header keeps the rightmost column. `"suffix"`: renames repeats `Id_2`, `Id_3`, … |
166
170
 
167
- Serializes a sheet to a CSV string with RFC-4180 quoting. A `Date` becomes a UTC
168
- ISO-8601 string, a `CellError` becomes its code (e.g. `#DIV/0!`), and a blank
169
- cell becomes an empty field. `delimiter` defaults to `,` and `eol` to `\n` (pass
170
- `\r\n` for Excel-style output).
171
+ ```ts
172
+ const rows = sheetToObjects(sheet, { skipBlankRows: true, duplicateHeaders: "suffix" });
173
+ // header ["Id", "Name", "Id"] → [{ Id: 1, Name: "Ada", Id_2: 7 }, …]
174
+ ```
175
+
176
+ ### `sheetToCsv(sheet: Sheet, options?: { delimiter?: string; eol?: string; dateFormat?: "iso" | "compact" }): string`
177
+
178
+ Serializes a sheet to a CSV string with RFC-4180 quoting. Each cell is rendered
179
+ with `cellToString` (below), so `dateFormat` works the same way. `delimiter`
180
+ defaults to `,` and `eol` to `\n` (pass `\r\n` for Excel-style output).
171
181
 
172
182
  ```ts
173
183
  import { readFirstSheet, sheetToCsv } from "xls-reader";
@@ -177,6 +187,22 @@ const csv = sheet ? sheetToCsv(sheet) : "";
177
187
  // "Name,Age\nAda,36\nAlan,41"
178
188
  ```
179
189
 
190
+ ### `cellToString(cell: Cell, options?: { dateFormat?: "iso" | "compact" }): string`
191
+
192
+ One cell as plain text, the same way `sheetToCsv` writes it: a blank cell becomes
193
+ `""`, a `CellError` becomes its code (e.g. `#DIV/0!`), and a `Date` becomes UTC
194
+ text. `dateFormat: "iso"` (the default) is `Date.toISOString()`; `"compact"`
195
+ gives `2024-04-02` for a date at UTC midnight and `2024-04-02T09:30:15Z`
196
+ otherwise.
197
+
198
+ ```ts
199
+ import { cellToString, readFirstSheet } from "xls-reader";
200
+
201
+ const rows = readFirstSheet(bytes)?.rows ?? [];
202
+ const text = rows.map((row) => row.map((cell) => cellToString(cell, { dateFormat: "compact" })));
203
+ // [["Name", "Born"], ["Ada", "1815-12-10"]]
204
+ ```
205
+
180
206
  ### `excelSerialToDate(serial: number, date1904: boolean): Date`
181
207
 
182
208
  The raw serial-number → `Date` (UTC) conversion, if you need it directly.
package/README.pt-BR.md CHANGED
@@ -163,18 +163,29 @@ Faz o parsing do workbook inteiro. Lança `XlsError` se os bytes não forem um
163
163
 
164
164
  A primeira planilha, para o caso de uma única aba.
165
165
 
166
- ### `sheetToObjects(sheet: Sheet, options?: { headerRow?: number }): RowObject[]`
166
+ ### `sheetToObjects(sheet: Sheet, options?: SheetToObjectsOptions): RowObject[]`
167
167
 
168
168
  Transforma as linhas de uma planilha em objetos com chaves vindas de uma linha
169
169
  de cabeçalho (a primeira, por padrão). Colunas com cabeçalho vazio são ignoradas
170
170
  e linhas curtas são preenchidas com `null`.
171
171
 
172
- ### `sheetToCsv(sheet: Sheet, options?: { delimiter?: string; eol?: string }): string`
172
+ | Opção | Padrão | O que faz |
173
+ | ------------------ | ------------- | ------------------------------------------------------------------------------------------------------------------ |
174
+ | `headerRow` | `0` | Linha (começando em 0) com as chaves; as linhas acima dela são ignoradas. |
175
+ | `skipBlankRows` | `false` | Descarta linhas em que todas as células são `null` ou texto só com espaços. |
176
+ | `duplicateHeaders` | `"overwrite"` | `"overwrite"`: um cabeçalho repetido fica com a coluna mais à direita. `"suffix"`: renomeia para `Id_2`, `Id_3`, … |
173
177
 
174
- Serializa uma planilha para uma string CSV com aspas no padrão RFC-4180. Um
175
- `Date` vira uma string ISO-8601 em UTC, um `CellError` vira o seu código (ex.:
176
- `#DIV/0!`) e uma célula em branco vira um campo vazio. `delimiter` é `,` por
177
- padrão e `eol` é `\n` (use `\r\n` para o formato do Excel).
178
+ ```ts
179
+ const rows = sheetToObjects(sheet, { skipBlankRows: true, duplicateHeaders: "suffix" });
180
+ // cabeçalho ["Id", "Name", "Id"] → [{ Id: 1, Name: "Ada", Id_2: 7 }, …]
181
+ ```
182
+
183
+ ### `sheetToCsv(sheet: Sheet, options?: { delimiter?: string; eol?: string; dateFormat?: "iso" | "compact" }): string`
184
+
185
+ Serializa uma planilha para uma string CSV com aspas no padrão RFC-4180. Cada
186
+ célula é convertida com `cellToString` (abaixo), então `dateFormat` funciona do
187
+ mesmo jeito. `delimiter` é `,` por padrão e `eol` é `\n` (use `\r\n` para o
188
+ formato do Excel).
178
189
 
179
190
  ```ts
180
191
  import { readFirstSheet, sheetToCsv } from "xls-reader";
@@ -184,6 +195,22 @@ const csv = sheet ? sheetToCsv(sheet) : "";
184
195
  // "Name,Age\nAda,36\nAlan,41"
185
196
  ```
186
197
 
198
+ ### `cellToString(cell: Cell, options?: { dateFormat?: "iso" | "compact" }): string`
199
+
200
+ Uma célula como texto, do mesmo jeito que o `sheetToCsv` escreve: uma célula em
201
+ branco vira `""`, um `CellError` vira o seu código (ex.: `#DIV/0!`) e um `Date`
202
+ vira texto em UTC. `dateFormat: "iso"` (o padrão) é o `Date.toISOString()`;
203
+ `"compact"` dá `2024-04-02` para uma data à meia-noite UTC e
204
+ `2024-04-02T09:30:15Z` nos outros casos.
205
+
206
+ ```ts
207
+ import { cellToString, readFirstSheet } from "xls-reader";
208
+
209
+ const rows = readFirstSheet(bytes)?.rows ?? [];
210
+ const text = rows.map((row) => row.map((cell) => cellToString(cell, { dateFormat: "compact" })));
211
+ // [["Name", "Born"], ["Ada", "1815-12-10"]]
212
+ ```
213
+
187
214
  ### `excelSerialToDate(serial: number, date1904: boolean): Date`
188
215
 
189
216
  A conversão bruta de número serial → `Date` (UTC), caso você precise dela
package/dist/cli.mjs CHANGED
@@ -939,21 +939,42 @@ Examples:
939
939
  npx xls-reader report.xls --visible-only > report.json
940
940
  `;
941
941
 
942
+ // src/cell-to-string.ts
943
+ /**
944
+ * Renders one cell as plain text: blank → `""`, `Date` → UTC text in the chosen
945
+ * `dateFormat`, `CellError` → its code (e.g. `#DIV/0!`), anything else via its
946
+ * JS string form. This is the exact rendering `sheetToCsv` uses per field, so
947
+ * importers that build their own rows don't have to re-derive it.
948
+ *
949
+ * @example
950
+ * cellToString(new Date(Date.UTC(2024, 3, 2)), { dateFormat: "compact" }) // "2024-04-02"
951
+ */
952
+ function cellToString(cell, options = {}) {
953
+ if (cell === null) return "";
954
+ if (cell instanceof Date) return dateToText(cell, options.dateFormat ?? "iso");
955
+ if (cell instanceof CellError) return cell.code;
956
+ return String(cell);
957
+ }
958
+ function dateToText(date, format) {
959
+ if (format === "iso") return date.toISOString();
960
+ if (format === "compact") return compactDate(date);
961
+ throw new XlsError(`dateFormat must be "iso" or "compact", got ${JSON.stringify(format)}`);
962
+ }
963
+ function compactDate(date) {
964
+ const iso = date.toISOString();
965
+ return iso.endsWith("T00:00:00.000Z") ? iso.slice(0, 10) : `${iso.slice(0, 19)}Z`;
966
+ }
967
+
942
968
  // src/sheet-to-csv.ts
943
969
  function sheetToCsv(sheet, options = {}) {
944
970
  const delimiter = options.delimiter ?? ",";
945
971
  const eol = options.eol ?? "\n";
972
+ const dateFormat = options.dateFormat ?? "iso";
946
973
  assertDelimiter(delimiter);
947
- return sheet.rows.map((row) => encodeRow(row, delimiter)).join(eol);
948
- }
949
- function encodeRow(row, delimiter) {
950
- return row.map((cell) => encodeField(cellToText(cell), delimiter)).join(delimiter);
974
+ return sheet.rows.map((row) => encodeRow(row, delimiter, dateFormat)).join(eol);
951
975
  }
952
- function cellToText(cell) {
953
- if (cell === null) return "";
954
- if (cell instanceof Date) return cell.toISOString();
955
- if (cell instanceof CellError) return cell.code;
956
- return String(cell);
976
+ function encodeRow(row, delimiter, dateFormat) {
977
+ return row.map((cell) => encodeField(cellToString(cell, { dateFormat }), delimiter)).join(delimiter);
957
978
  }
958
979
  function encodeField(text, delimiter) {
959
980
  if (!text.includes(delimiter) && !/["\r\n]/.test(text)) return text;
@@ -970,11 +991,37 @@ function sheetToObjects(sheet, options = {}) {
970
991
  assertHeaderRow(headerRow);
971
992
  const header = sheet.rows[headerRow];
972
993
  if (header === void 0) return [];
973
- const keys = headerKeys(header);
974
- return sheet.rows.slice(headerRow + 1).map((row) => rowToObject(row, keys));
994
+ const keys = headerKeys(header, options.duplicateHeaders ?? "overwrite");
995
+ const dataRows = sheet.rows.slice(headerRow + 1);
996
+ return (options.skipBlankRows ? dataRows.filter((row) => !isBlankRow(row)) : dataRows).map((row) => rowToObject(row, keys));
997
+ }
998
+ function headerKeys(row, mode) {
999
+ const keys = row.map((cell) => toKey(cell));
1000
+ if (mode === "overwrite") return keys;
1001
+ if (mode === "suffix") return suffixDuplicates(keys);
1002
+ throw new XlsError(`duplicateHeaders must be "overwrite" or "suffix", got ${JSON.stringify(mode)}`);
1003
+ }
1004
+ function suffixDuplicates(keys) {
1005
+ const taken = new Set(keys.filter((key) => key !== null));
1006
+ const seen = /* @__PURE__ */ new Set();
1007
+ return keys.map((key) => {
1008
+ if (key === null) return null;
1009
+ if (!seen.has(key)) {
1010
+ seen.add(key);
1011
+ return key;
1012
+ }
1013
+ const renamed = firstFreeSuffix(key, taken);
1014
+ taken.add(renamed);
1015
+ return renamed;
1016
+ });
1017
+ }
1018
+ function firstFreeSuffix(key, taken) {
1019
+ let n = 2;
1020
+ while (taken.has(`${key}_${n}`)) n += 1;
1021
+ return `${key}_${n}`;
975
1022
  }
976
- function headerKeys(row) {
977
- return row.map((cell) => toKey(cell));
1023
+ function isBlankRow(row) {
1024
+ return row.every((cell) => cell === null || typeof cell === "string" && cell.trim() === "");
978
1025
  }
979
1026
  function toKey(cell) {
980
1027
  if (cell === null) return null;
package/dist/index.cjs CHANGED
@@ -862,11 +862,37 @@ function sheetToObjects(sheet, options = {}) {
862
862
  assertHeaderRow(headerRow);
863
863
  const header = sheet.rows[headerRow];
864
864
  if (header === void 0) return [];
865
- const keys = headerKeys(header);
866
- return sheet.rows.slice(headerRow + 1).map((row) => rowToObject(row, keys));
865
+ const keys = headerKeys(header, options.duplicateHeaders ?? "overwrite");
866
+ const dataRows = sheet.rows.slice(headerRow + 1);
867
+ return (options.skipBlankRows ? dataRows.filter((row) => !isBlankRow(row)) : dataRows).map((row) => rowToObject(row, keys));
868
+ }
869
+ function headerKeys(row, mode) {
870
+ const keys = row.map((cell) => toKey(cell));
871
+ if (mode === "overwrite") return keys;
872
+ if (mode === "suffix") return suffixDuplicates(keys);
873
+ throw new XlsError(`duplicateHeaders must be "overwrite" or "suffix", got ${JSON.stringify(mode)}`);
874
+ }
875
+ function suffixDuplicates(keys) {
876
+ const taken = new Set(keys.filter((key) => key !== null));
877
+ const seen = /* @__PURE__ */ new Set();
878
+ return keys.map((key) => {
879
+ if (key === null) return null;
880
+ if (!seen.has(key)) {
881
+ seen.add(key);
882
+ return key;
883
+ }
884
+ const renamed = firstFreeSuffix(key, taken);
885
+ taken.add(renamed);
886
+ return renamed;
887
+ });
867
888
  }
868
- function headerKeys(row) {
869
- return row.map((cell) => toKey(cell));
889
+ function firstFreeSuffix(key, taken) {
890
+ let n = 2;
891
+ while (taken.has(`${key}_${n}`)) n += 1;
892
+ return `${key}_${n}`;
893
+ }
894
+ function isBlankRow(row) {
895
+ return row.every((cell) => cell === null || typeof cell === "string" && cell.trim() === "");
870
896
  }
871
897
  function toKey(cell) {
872
898
  if (cell === null) return null;
@@ -886,21 +912,42 @@ function assertHeaderRow(headerRow) {
886
912
  throw new XlsError(`headerRow must be a non-negative integer, got ${JSON.stringify(headerRow)}`);
887
913
  }
888
914
 
915
+ // src/cell-to-string.ts
916
+ /**
917
+ * Renders one cell as plain text: blank → `""`, `Date` → UTC text in the chosen
918
+ * `dateFormat`, `CellError` → its code (e.g. `#DIV/0!`), anything else via its
919
+ * JS string form. This is the exact rendering `sheetToCsv` uses per field, so
920
+ * importers that build their own rows don't have to re-derive it.
921
+ *
922
+ * @example
923
+ * cellToString(new Date(Date.UTC(2024, 3, 2)), { dateFormat: "compact" }) // "2024-04-02"
924
+ */
925
+ function cellToString(cell, options = {}) {
926
+ if (cell === null) return "";
927
+ if (cell instanceof Date) return dateToText(cell, options.dateFormat ?? "iso");
928
+ if (cell instanceof CellError) return cell.code;
929
+ return String(cell);
930
+ }
931
+ function dateToText(date, format) {
932
+ if (format === "iso") return date.toISOString();
933
+ if (format === "compact") return compactDate(date);
934
+ throw new XlsError(`dateFormat must be "iso" or "compact", got ${JSON.stringify(format)}`);
935
+ }
936
+ function compactDate(date) {
937
+ const iso = date.toISOString();
938
+ return iso.endsWith("T00:00:00.000Z") ? iso.slice(0, 10) : `${iso.slice(0, 19)}Z`;
939
+ }
940
+
889
941
  // src/sheet-to-csv.ts
890
942
  function sheetToCsv(sheet, options = {}) {
891
943
  const delimiter = options.delimiter ?? ",";
892
944
  const eol = options.eol ?? "\n";
945
+ const dateFormat = options.dateFormat ?? "iso";
893
946
  assertDelimiter(delimiter);
894
- return sheet.rows.map((row) => encodeRow(row, delimiter)).join(eol);
947
+ return sheet.rows.map((row) => encodeRow(row, delimiter, dateFormat)).join(eol);
895
948
  }
896
- function encodeRow(row, delimiter) {
897
- return row.map((cell) => encodeField(cellToText(cell), delimiter)).join(delimiter);
898
- }
899
- function cellToText(cell) {
900
- if (cell === null) return "";
901
- if (cell instanceof Date) return cell.toISOString();
902
- if (cell instanceof CellError) return cell.code;
903
- return String(cell);
949
+ function encodeRow(row, delimiter, dateFormat) {
950
+ return row.map((cell) => encodeField(cellToString(cell, { dateFormat }), delimiter)).join(delimiter);
904
951
  }
905
952
  function encodeField(text, delimiter) {
906
953
  if (!text.includes(delimiter) && !/["\r\n]/.test(text)) return text;
@@ -913,6 +960,7 @@ function assertDelimiter(delimiter) {
913
960
 
914
961
  exports.CellError = CellError;
915
962
  exports.XlsError = XlsError;
963
+ exports.cellToString = cellToString;
916
964
  exports.excelSerialToDate = excelSerialToDate;
917
965
  exports.readFirstSheet = readFirstSheet;
918
966
  exports.readXls = readXls;