xls-reader 0.1.1 → 0.1.2

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,13 @@
1
1
  # xls-reader
2
2
 
3
+ ## 0.1.2
4
+
5
+ ### Patch Changes
6
+
7
+ - [#22](https://github.com/zanlucathiago/xls-reader/pull/22) [`a00d7e1`](https://github.com/zanlucathiago/xls-reader/commit/a00d7e16c33ab57909046f571dd40e989d632fc1) Thanks [@zanlucathiago](https://github.com/zanlucathiago)! - Docs & discoverability: sharpen the npm description and keywords, and add an
8
+ "Convert an .xls to JSON" example plus an FAQ to the README (English and
9
+ pt-BR). No API changes.
10
+
3
11
  ## 0.1.1
4
12
 
5
13
  ### Patch Changes
package/README.md CHANGED
@@ -1,8 +1,7 @@
1
- <h1 align="center">xls-reader</h1>
2
-
3
1
  <p align="center">
4
- Zero-dependency reader for <strong>legacy <code>.xls</code></strong> files (BIFF8 — Excel 97–2003).<br />
5
- Returns each worksheet as a grid of typed cells: strings, numbers, booleans, and dates.
2
+ <a href="https://www.npmjs.com/package/xls-reader">
3
+ <img src="https://raw.githubusercontent.com/zanlucathiago/xls-reader/main/assets/banner.png" alt="xls-reader — zero-dependency reader for legacy .xls (BIFF8 / Excel 97–2003)" width="820" />
4
+ </a>
6
5
  </p>
7
6
 
8
7
  <p align="center">
@@ -15,6 +14,10 @@
15
14
  <a href="./LICENSE"><img src="https://img.shields.io/npm/l/xls-reader.svg?color=blue" alt="MIT license" /></a>
16
15
  </p>
17
16
 
17
+ <p align="center">
18
+ <strong>English</strong> · <a href="./README.pt-BR.md">Português (BR)</a>
19
+ </p>
20
+
18
21
  Runs in Node and the browser — it only needs `Uint8Array` / `DataView`. It ships
19
22
  as **~3.8 KB min+gzip with zero runtime dependencies**, dual ESM/CJS, fully typed,
20
23
  and published to npm with [provenance](https://docs.npmjs.com/generating-provenance-statements).
@@ -28,10 +31,12 @@ npm install xls-reader
28
31
 
29
32
  - [Why this exists](#why-this-exists)
30
33
  - [Usage](#usage)
34
+ - [Convert an .xls to JSON](#convert-an-xls-to-json)
31
35
  - [API](#api)
32
36
  - [Comparison](#comparison)
33
37
  - [Supported](#supported)
34
38
  - [Limitations](#limitations)
39
+ - [FAQ](#faq)
35
40
  - [Contributing](#contributing)
36
41
 
37
42
  ## Why this exists
@@ -84,6 +89,22 @@ input.addEventListener("change", async () => {
84
89
  });
85
90
  ```
86
91
 
92
+ ## Convert an .xls to JSON
93
+
94
+ Use the first row as the keys to turn a sheet into an array of JSON objects:
95
+
96
+ ```ts
97
+ import { readFirstSheet } from "xls-reader";
98
+
99
+ const sheet = readFirstSheet(bytes);
100
+ const [header = [], ...body] = sheet?.rows ?? [];
101
+
102
+ const json = body.map((row) =>
103
+ Object.fromEntries(header.map((key, i) => [String(key), row[i] ?? null])),
104
+ );
105
+ // [{ Emitente: "BANCO X S/A", Taxa: 1.1, Data: 2024-04-02T00:00:00.000Z }, ...]
106
+ ```
107
+
87
108
  Handling non-`.xls` input:
88
109
 
89
110
  ```ts
@@ -169,6 +190,43 @@ of a legacy `.xls`.
169
190
  - Dates before 1900-03-01 in the 1900 system are off by one day (Excel's
170
191
  historical leap-year bug); real-world data is unaffected.
171
192
 
193
+ ## FAQ
194
+
195
+ ### How do I read an `.xls` file in Node.js?
196
+
197
+ Install `xls-reader`, read the file into bytes, and call `readXls` — no other
198
+ setup, no native modules:
199
+
200
+ ```ts
201
+ import { readFile } from "node:fs/promises";
202
+ import { readXls } from "xls-reader";
203
+
204
+ const workbook = readXls(await readFile("report.xls"));
205
+ ```
206
+
207
+ ### Is this a SheetJS (`xlsx`) alternative?
208
+
209
+ For **reading legacy `.xls`**, yes. SheetJS no longer publishes to npm, so
210
+ `xls-reader` is a small, npm-published, zero-dependency option when all you need
211
+ is the cell values. It does not write files or read `.xlsx` — for that, use
212
+ SheetJS or ExcelJS.
213
+
214
+ ### Can it read `.xlsx` files?
215
+
216
+ No. `.xlsx` is the newer OOXML (zipped XML) format — a completely different
217
+ container. `xls-reader` handles the older binary BIFF8 `.xls` only. Use
218
+ [ExcelJS](https://github.com/exceljs/exceljs) for `.xlsx`.
219
+
220
+ ### How do I convert an `.xls` to JSON?
221
+
222
+ See [Convert an .xls to JSON](#convert-an-xls-to-json) above — map each data row
223
+ onto the header row with `Object.fromEntries`.
224
+
225
+ ### Does it work in the browser?
226
+
227
+ Yes. It only uses `Uint8Array` / `DataView`, so pass an `ArrayBuffer` (e.g. from
228
+ a file `<input>` or `fetch`) straight to `readXls`.
229
+
172
230
  ## Contributing
173
231
 
174
232
  Bug reports, sample files, and PRs are very welcome — see
@@ -0,0 +1,249 @@
1
+ <p align="center">
2
+ <a href="https://www.npmjs.com/package/xls-reader">
3
+ <img src="https://raw.githubusercontent.com/zanlucathiago/xls-reader/main/assets/banner.png" alt="xls-reader — leitor sem dependências para .xls legado (BIFF8 / Excel 97–2003)" width="820" />
4
+ </a>
5
+ </p>
6
+
7
+ <p align="center">
8
+ <a href="https://www.npmjs.com/package/xls-reader"><img src="https://img.shields.io/npm/v/xls-reader.svg?color=cb3837&logo=npm" alt="versão no npm" /></a>
9
+ <a href="https://www.npmjs.com/package/xls-reader"><img src="https://img.shields.io/npm/dm/xls-reader.svg?color=cb3837&logo=npm" alt="downloads no npm" /></a>
10
+ <a href="https://github.com/zanlucathiago/xls-reader/actions/workflows/ci.yml"><img src="https://github.com/zanlucathiago/xls-reader/actions/workflows/ci.yml/badge.svg" alt="status do CI" /></a>
11
+ <a href="https://codecov.io/gh/zanlucathiago/xls-reader"><img src="https://codecov.io/gh/zanlucathiago/xls-reader/branch/main/graph/badge.svg" alt="cobertura" /></a>
12
+ <a href="https://bundlephobia.com/package/xls-reader"><img src="https://img.shields.io/bundlephobia/minzip/xls-reader.svg?label=min%2Bgzip" alt="tamanho do bundle" /></a>
13
+ <img src="https://img.shields.io/badge/dependencies-0-brightgreen.svg" alt="zero dependências" />
14
+ <a href="./LICENSE"><img src="https://img.shields.io/npm/l/xls-reader.svg?color=blue" alt="licença MIT" /></a>
15
+ </p>
16
+
17
+ <p align="center">
18
+ <a href="./README.md">English</a> · <strong>Português (BR)</strong>
19
+ </p>
20
+
21
+ Roda no Node e no navegador — só precisa de `Uint8Array` / `DataView`. São
22
+ **~3,8 KB min+gzip com zero dependências de runtime**, saída dupla ESM/CJS,
23
+ totalmente tipado, e publicado no npm com
24
+ [provenance](https://docs.npmjs.com/generating-provenance-statements).
25
+
26
+ ```bash
27
+ npm install xls-reader
28
+ # ou: pnpm add xls-reader / yarn add xls-reader
29
+ ```
30
+
31
+ ## Conteúdo
32
+
33
+ - [Por que isso existe](#por-que-isso-existe)
34
+ - [Uso](#uso)
35
+ - [Converter um .xls para JSON](#converter-um-xls-para-json)
36
+ - [API](#api)
37
+ - [Comparação](#comparação)
38
+ - [Suportado](#suportado)
39
+ - [Limitações](#limitações)
40
+ - [FAQ](#faq)
41
+ - [Contribuindo](#contribuindo)
42
+
43
+ ## Por que isso existe
44
+
45
+ Leitores modernos como o [ExcelJS](https://github.com/exceljs/exceljs) só lidam
46
+ com o formato mais novo `.xlsx` (OOXML). O leitor de `.xls` de facto,
47
+ [SheetJS](https://sheetjs.com), **não publica mais no registro do npm** — sua
48
+ última versão no npm (`0.18.5`) está congelada com vulnerabilidades conhecidas, e
49
+ as correções saem apenas do CDN próprio dele. Instalar de um CDN significa que o
50
+ `npm audit` e o Dependabot não enxergam o pacote, então você perde os alertas
51
+ automáticos de vulnerabilidade.
52
+
53
+ O `xls-reader` é uma alternativa pequena, focada e **publicada no npm** para o
54
+ caso comum: _ler as células de um `.xls` legado_. Sem dependências, licença MIT,
55
+ coberto pelas mesmas ferramentas de supply-chain do resto da sua árvore.
56
+
57
+ ## Uso
58
+
59
+ ```ts
60
+ import { readFile } from "node:fs/promises";
61
+ import { readXls } from "xls-reader";
62
+
63
+ const workbook = readXls(await readFile("posicao.xls"));
64
+
65
+ for (const sheet of workbook.sheets) {
66
+ console.log(sheet.name);
67
+ for (const row of sheet.rows) {
68
+ console.log(row); // ex.: ["BANCO DAYCOVAL S/A", "CDB", "CDI", 1.1, Date(2024-04-02), 1000, ...]
69
+ }
70
+ }
71
+ ```
72
+
73
+ Atalho para uma única planilha:
74
+
75
+ ```ts
76
+ import { readFirstSheet } from "xls-reader";
77
+
78
+ const sheet = readFirstSheet(bytes);
79
+ ```
80
+
81
+ No navegador (ex.: a partir de um `<input>` de arquivo):
82
+
83
+ ```ts
84
+ import { readXls } from "xls-reader";
85
+
86
+ input.addEventListener("change", async () => {
87
+ const file = input.files?.[0];
88
+ if (!file) return;
89
+ const workbook = readXls(await file.arrayBuffer());
90
+ console.table(workbook.sheets[0]?.rows);
91
+ });
92
+ ```
93
+
94
+ ## Converter um .xls para JSON
95
+
96
+ Use a primeira linha como chaves para transformar uma planilha em um array de
97
+ objetos JSON:
98
+
99
+ ```ts
100
+ import { readFirstSheet } from "xls-reader";
101
+
102
+ const sheet = readFirstSheet(bytes);
103
+ const [header = [], ...body] = sheet?.rows ?? [];
104
+
105
+ const json = body.map((row) =>
106
+ Object.fromEntries(header.map((key, i) => [String(key), row[i] ?? null])),
107
+ );
108
+ // [{ Emitente: "BANCO X S/A", Taxa: 1.1, Data: 2024-04-02T00:00:00.000Z }, ...]
109
+ ```
110
+
111
+ Tratando uma entrada que não é `.xls`:
112
+
113
+ ```ts
114
+ import { readXls, XlsError } from "xls-reader";
115
+
116
+ try {
117
+ const workbook = readXls(bytes);
118
+ } catch (err) {
119
+ if (err instanceof XlsError) {
120
+ // Não é um .xls BIFF — ex.: é na verdade um .xlsx, CSV ou HTML rotulado como .xls
121
+ console.error(err.message);
122
+ } else {
123
+ throw err;
124
+ }
125
+ }
126
+ ```
127
+
128
+ ## API
129
+
130
+ ### `readXls(data: ArrayBuffer | Uint8Array): Workbook`
131
+
132
+ Faz o parsing do workbook inteiro. Lança `XlsError` se os bytes não forem um
133
+ `.xls` BIFF.
134
+
135
+ ### `readFirstSheet(data): Sheet | undefined`
136
+
137
+ A primeira planilha, para o caso de uma única aba.
138
+
139
+ ### `excelSerialToDate(serial: number, date1904: boolean): Date`
140
+
141
+ A conversão bruta de número serial → `Date` (UTC), caso você precise dela
142
+ diretamente.
143
+
144
+ ### Tipos
145
+
146
+ ```ts
147
+ type Cell = string | number | boolean | Date | null;
148
+
149
+ interface Sheet {
150
+ name: string;
151
+ rows: Cell[][]; // densa, preenchida com null até a última coluna usada
152
+ }
153
+
154
+ interface Workbook {
155
+ sheets: Sheet[];
156
+ }
157
+ ```
158
+
159
+ - **Números** voltam como `number` (tanto na codificação `NUMBER` quanto na
160
+ compacta `RK`).
161
+ - **Datas** — um número cujo formato de célula é de data/hora (embutido ou
162
+ customizado) volta como `Date` (UTC). Use `excelSerialToDate` se precisar da
163
+ conversão bruta.
164
+ - Células **em branco / de erro** viram `null`.
165
+
166
+ ## Comparação
167
+
168
+ | | **xls-reader** | SheetJS (`xlsx`) | ExcelJS |
169
+ | ------------------------------------- | -------------- | ------------------------ | ------- |
170
+ | Lê `.xls` legado (BIFF8) | ✅ | ✅ | ❌ |
171
+ | Lê `.xlsx` (OOXML) | ❌ | ✅ | ✅ |
172
+ | Correções recentes no registro do npm | ✅ | ⚠️ congelado em `0.18.5` | ✅ |
173
+ | Dependências de runtime | **0** | várias | várias |
174
+ | Tamanho de instalação | ~4 KB min+gzip | grande | grande |
175
+ | Atestado de provenance no npm | ✅ | ❌ | ❌ |
176
+ | Escreve arquivos / estilos / gráficos | ❌ | ✅ | ✅ |
177
+
178
+ Se você precisa **escrever** planilhas, estilizar células ou ler `.xlsx`, use o
179
+ ExcelJS ou o SheetJS. O `xls-reader` faz uma coisa de propósito: extrair os
180
+ valores de um `.xls` legado.
181
+
182
+ ## Suportado
183
+
184
+ - Container OLE2 / Compound File (streams normais **e** mini streams).
185
+ - Registros BIFF8: `LABELSST`, `LABEL`, `RSTRING`, `NUMBER`, `RK`, `MULRK`,
186
+ `BLANK`, `MULBLANK`, `BOOLERR`, `FORMULA` (+ seu resultado `STRING`).
187
+ - Tabela de strings compartilhadas (`SST`), incluindo strings divididas entre
188
+ registros `CONTINUE`.
189
+ - Detecção de datas via `XF` + `FORMAT`, e os sistemas de data 1900 / 1904.
190
+
191
+ ## Limitações
192
+
193
+ - Somente leitura, e lê **valores** — não estilos, geometria de células
194
+ mescladas ou gráficos.
195
+ - Apenas BIFF8 (Excel 97+). Não lê os bem mais antigos BIFF5/BIFF2, nem os
196
+ arquivos HTML/XML que algumas ferramentas rotulam erradamente como `.xls`
197
+ (confira os magic bytes).
198
+ - Workbooks criptografados não são suportados.
199
+ - Datas anteriores a 1900-03-01 no sistema 1900 ficam com um dia de diferença
200
+ (o bug histórico de ano bissexto do Excel); dados do mundo real não são
201
+ afetados.
202
+
203
+ ## FAQ
204
+
205
+ ### Como leio um arquivo `.xls` no Node.js?
206
+
207
+ Instale o `xls-reader`, leia o arquivo em bytes e chame `readXls` — sem outra
208
+ configuração, sem módulos nativos:
209
+
210
+ ```ts
211
+ import { readFile } from "node:fs/promises";
212
+ import { readXls } from "xls-reader";
213
+
214
+ const workbook = readXls(await readFile("relatorio.xls"));
215
+ ```
216
+
217
+ ### É uma alternativa ao SheetJS (`xlsx`)?
218
+
219
+ Para **ler `.xls` legado**, sim. O SheetJS não publica mais no npm, então o
220
+ `xls-reader` é uma opção pequena, publicada no npm e sem dependências quando você
221
+ só precisa dos valores das células. Ele não escreve arquivos nem lê `.xlsx` —
222
+ para isso, use SheetJS ou ExcelJS.
223
+
224
+ ### Consegue ler arquivos `.xlsx`?
225
+
226
+ Não. `.xlsx` é o formato mais novo OOXML (XML zipado) — um container totalmente
227
+ diferente. O `xls-reader` lida apenas com o `.xls` binário BIFF8, mais antigo.
228
+ Use o [ExcelJS](https://github.com/exceljs/exceljs) para `.xlsx`.
229
+
230
+ ### Como converto um `.xls` para JSON?
231
+
232
+ Veja [Converter um .xls para JSON](#converter-um-xls-para-json) acima — mapeie
233
+ cada linha de dados na linha de cabeçalho com `Object.fromEntries`.
234
+
235
+ ### Funciona no navegador?
236
+
237
+ Sim. Ele só usa `Uint8Array` / `DataView`, então passe um `ArrayBuffer` (ex.: de
238
+ um `<input>` de arquivo ou `fetch`) direto para o `readXls`.
239
+
240
+ ## Contribuindo
241
+
242
+ Relatos de bug, arquivos de exemplo e PRs são muito bem-vindos — veja
243
+ [CONTRIBUTING.md](./CONTRIBUTING.md). Leia também o
244
+ [Código de Conduta](./CODE_OF_CONDUCT.md). Para reportar um problema de
245
+ segurança, veja a [Política de Segurança](./SECURITY.md).
246
+
247
+ ## Licença
248
+
249
+ [MIT](./LICENSE) © Thiago Zanluca
package/package.json CHANGED
@@ -1,20 +1,26 @@
1
1
  {
2
2
  "name": "xls-reader",
3
- "version": "0.1.1",
4
- "description": "Zero-dependency reader for legacy .xls (BIFF8 / Excel 97-2003) files. Returns each sheet as a grid of typed cells.",
3
+ "version": "0.1.2",
4
+ "description": "Zero-dependency .xls (BIFF8 / Excel 97-2003) reader for Node and the browser — a lightweight SheetJS alternative that returns each worksheet as typed cells.",
5
5
  "keywords": [
6
6
  "xls",
7
- "biff8",
7
+ "xls-reader",
8
+ "read-xls",
9
+ "xls-to-json",
10
+ "xls-parser",
8
11
  "excel",
12
+ "excel-reader",
13
+ "read-excel",
14
+ "biff8",
15
+ "biff",
9
16
  "spreadsheet",
10
- "ole2",
11
- "cfb",
17
+ "spreadsheet-parser",
12
18
  "legacy-excel",
13
- "parser",
14
- "xls-parser",
15
- "read-xls",
16
19
  "sheetjs-alternative",
17
20
  "xlrd",
21
+ "ole2",
22
+ "cfb",
23
+ "parser",
18
24
  "zero-dependency",
19
25
  "typescript",
20
26
  "browser",
@@ -44,6 +50,7 @@
44
50
  "files": [
45
51
  "dist",
46
52
  "README.md",
53
+ "README.pt-BR.md",
47
54
  "CHANGELOG.md",
48
55
  "LICENSE"
49
56
  ],
@@ -55,14 +62,14 @@
55
62
  "@changesets/changelog-github": "^0.7.0",
56
63
  "@changesets/cli": "^2.31.0",
57
64
  "@eslint/js": "^10.0.1",
58
- "@types/node": "^22.20.0",
65
+ "@types/node": "^26.0.0",
59
66
  "@vitest/coverage-v8": "^4.1.9",
60
67
  "eslint": "^10.6.0",
61
68
  "prettier": "^3.4.2",
62
69
  "tsup": "^8.3.5",
63
70
  "typescript": "^6.0.3",
64
71
  "typescript-eslint": "^8.18.1",
65
- "vite": "^7.3.6",
72
+ "vite": "^8.0.16",
66
73
  "vitest": "^4.1.9"
67
74
  },
68
75
  "scripts": {