javascript-excel 1.0.3 → 2.0.0-alpha.1
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/README.md +50 -2
- package/dist/auto-width-2oBzjeNG.d.cts +11 -0
- package/dist/auto-width-CT-BihTW.d.ts +10 -0
- package/dist/csv.cjs +623 -0
- package/dist/csv.d.cts +89 -0
- package/dist/csv.d.ts +89 -0
- package/dist/csv.js +618 -0
- package/dist/dom.cjs +464 -0
- package/dist/dom.d.cts +78 -0
- package/dist/dom.d.ts +78 -0
- package/dist/dom.js +461 -0
- package/dist/errors-CvGlfw0E.js +28 -0
- package/dist/errors-DOPrrGS4.cjs +69 -0
- package/dist/index.cjs +1424 -0
- package/dist/index.d.cts +140 -0
- package/dist/index.d.ts +140 -0
- package/dist/index.js +1397 -0
- package/dist/infer-BR-J9BZa.js +88 -0
- package/dist/infer-D9EC9vJ-.cjs +105 -0
- package/dist/iso-date-B22IvwL1.js +21 -0
- package/dist/iso-date-BSUsPSWO.cjs +26 -0
- package/dist/numfmt-B-TlCgr7.cjs +476 -0
- package/dist/numfmt-DEm0sYBJ.js +399 -0
- package/dist/read.cjs +2899 -0
- package/dist/read.d.cts +88 -0
- package/dist/read.d.ts +88 -0
- package/dist/read.js +2895 -0
- package/dist/sheet-names-CDsVK15c.js +831 -0
- package/dist/sheet-names-Cm-IhbBk.cjs +1004 -0
- package/dist/signal-Dz0ZYe6d.d.cts +13 -0
- package/dist/signal-Dz0ZYe6d.d.ts +13 -0
- package/dist/warnings-C_12PT4t.d.cts +410 -0
- package/dist/warnings-DXJKe1lx.d.ts +410 -0
- package/dist/worker.cjs +11 -0
- package/dist/worker.d.cts +8 -0
- package/dist/worker.d.ts +8 -0
- package/dist/worker.js +10 -0
- package/dist/write-C5JgeIar.d.cts +29 -0
- package/dist/write-CYpLGuzl.d.ts +29 -0
- package/package.json +67 -51
- package/.babelrc +0 -10
- package/.circleci/config.yml +0 -39
- package/lib/index.d.ts +0 -1
- package/lib/index.js +0 -22
- package/lib/javascript-excel.js +0 -17703
- package/src/index.tsx +0 -11
- package/test/unit/sample.spec.js +0 -5
- package/tsconfig.json +0 -54
- package/webpack.config.js +0 -19
- /package/{LICENSE.md → LICENSE} +0 -0
package/dist/dom.cjs
ADDED
|
@@ -0,0 +1,464 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
const require_sheet_names = require("./sheet-names-Cm-IhbBk.cjs");
|
|
3
|
+
const require_errors = require("./errors-DOPrrGS4.cjs");
|
|
4
|
+
// src/auto-width.ts
|
|
5
|
+
/**
|
|
6
|
+
* Auto column widths for builders (docs/api.md §4.3, §5.4).
|
|
7
|
+
*/
|
|
8
|
+
/** Estimated width in characters per column: widest `cellText` + 2 padding, clamped to [min, max]. */
|
|
9
|
+
function autoWidths(rows, options = {}) {
|
|
10
|
+
const min = options.min ?? require_sheet_names.AUTO_WIDTH.min;
|
|
11
|
+
const max = Math.min(255, options.max ?? require_sheet_names.AUTO_WIDTH.max);
|
|
12
|
+
const limit = Math.min(rows.length, options.sampleRows ?? rows.length);
|
|
13
|
+
const widest = [];
|
|
14
|
+
for (let r = 0; r < limit; r++) {
|
|
15
|
+
const row = rows[r];
|
|
16
|
+
if (!row) continue;
|
|
17
|
+
for (let c = 0; c < row.length; c++) {
|
|
18
|
+
const w = require_sheet_names.textWidth(require_sheet_names.cellText(row[c]));
|
|
19
|
+
if (w > (widest[c] ?? 0)) widest[c] = w;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
return Array.from(widest, (w) => Math.min(max, Math.max(min, (w ?? 0) + require_sheet_names.AUTO_WIDTH.padding)));
|
|
23
|
+
}
|
|
24
|
+
// src/internal/css-color.ts
|
|
25
|
+
/** CSS colour values to RRGGBB, for computed-style mapping in javascript-excel/dom. */
|
|
26
|
+
const NAMED = {
|
|
27
|
+
black: "000000",
|
|
28
|
+
white: "FFFFFF",
|
|
29
|
+
red: "FF0000",
|
|
30
|
+
lime: "00FF00",
|
|
31
|
+
green: "008000",
|
|
32
|
+
blue: "0000FF",
|
|
33
|
+
yellow: "FFFF00",
|
|
34
|
+
cyan: "00FFFF",
|
|
35
|
+
aqua: "00FFFF",
|
|
36
|
+
magenta: "FF00FF",
|
|
37
|
+
fuchsia: "FF00FF",
|
|
38
|
+
silver: "C0C0C0",
|
|
39
|
+
gray: "808080",
|
|
40
|
+
grey: "808080",
|
|
41
|
+
maroon: "800000",
|
|
42
|
+
olive: "808000",
|
|
43
|
+
purple: "800080",
|
|
44
|
+
teal: "008080",
|
|
45
|
+
navy: "000080",
|
|
46
|
+
orange: "FFA500"
|
|
47
|
+
};
|
|
48
|
+
/** A CSS colour as RRGGBB, or undefined for transparent or unparseable values. */
|
|
49
|
+
function cssColor(value) {
|
|
50
|
+
const v = value.trim().toLowerCase();
|
|
51
|
+
if (!v || v === "transparent" || v === "currentcolor" || v === "inherit" || v === "initial") return void 0;
|
|
52
|
+
const hex = /^#([0-9a-f]{3,8})$/.exec(v)?.[1];
|
|
53
|
+
if (hex) {
|
|
54
|
+
if (hex.length === 3 || hex.length === 4) {
|
|
55
|
+
if (hex.length === 4 && hex[3] === "0") return void 0;
|
|
56
|
+
return hex.slice(0, 3).split("").map((c) => c + c).join("").toUpperCase();
|
|
57
|
+
}
|
|
58
|
+
if (hex.length === 6) return hex.toUpperCase();
|
|
59
|
+
if (hex.length === 8) return hex.slice(6) === "00" ? void 0 : hex.slice(0, 6).toUpperCase();
|
|
60
|
+
return;
|
|
61
|
+
}
|
|
62
|
+
const m = /^rgba?\(\s*([\d.]+%?)[\s,]+([\d.]+%?)[\s,]+([\d.]+%?)(?:\s*[,/]\s*([\d.]+%?))?\s*\)$/.exec(v);
|
|
63
|
+
if (m) {
|
|
64
|
+
const ch = (s) => Math.round(Math.min(255, Math.max(0, s.endsWith("%") ? parseFloat(s) * 255 / 100 : parseFloat(s))));
|
|
65
|
+
if (m[4] !== void 0) {
|
|
66
|
+
if (!((m[4].endsWith("%") ? parseFloat(m[4]) / 100 : parseFloat(m[4])) > 0)) return void 0;
|
|
67
|
+
}
|
|
68
|
+
return [
|
|
69
|
+
m[1],
|
|
70
|
+
m[2],
|
|
71
|
+
m[3]
|
|
72
|
+
].map((s) => ch(s).toString(16).padStart(2, "0")).join("").toUpperCase();
|
|
73
|
+
}
|
|
74
|
+
return NAMED[v];
|
|
75
|
+
}
|
|
76
|
+
function isElement(n) {
|
|
77
|
+
return n.nodeType === 1;
|
|
78
|
+
}
|
|
79
|
+
// src/dom.ts
|
|
80
|
+
/**
|
|
81
|
+
* javascript-excel/dom: HTML table input and file download (docs/api.md §5.4).
|
|
82
|
+
*
|
|
83
|
+
* The only module that touches the DOM. Importing it never reads a global, so
|
|
84
|
+
* it is safe during server-side rendering; the DOM is used only inside the
|
|
85
|
+
* functions, and a table is read through its own window (iframes work).
|
|
86
|
+
*/
|
|
87
|
+
const DEFAULT_IGNORE = "[data-export-ignore]";
|
|
88
|
+
const XLSX_MIME = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
|
|
89
|
+
/** HTML's limits on colspan and rowspan. */
|
|
90
|
+
const MAX_COLSPAN = 1e3;
|
|
91
|
+
const MAX_ROWSPAN = 65534;
|
|
92
|
+
/**
|
|
93
|
+
* How long the object URL stays valid after the click. Browsers start the
|
|
94
|
+
* download asynchronously, and Safari needs the URL for a while; 40 s is the
|
|
95
|
+
* delay FileSaver.js uses. Not measured here.
|
|
96
|
+
*/
|
|
97
|
+
const DOWNLOAD_REVOKE_DELAY_MS = 4e4;
|
|
98
|
+
function mimeFor(filename, data) {
|
|
99
|
+
const ext = /\.([A-Za-z0-9]+)$/.exec(filename)?.[1]?.toLowerCase();
|
|
100
|
+
if (ext === "xlsx") return XLSX_MIME;
|
|
101
|
+
if (ext === "csv") return "text/csv;charset=utf-8";
|
|
102
|
+
return typeof data === "string" ? "text/plain;charset=utf-8" : "application/octet-stream";
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* Saves data as a file in the browser: creates an object URL, clicks a
|
|
106
|
+
* temporary `<a download>` and revokes the URL after DOWNLOAD_REVOKE_DELAY_MS.
|
|
107
|
+
* A string is encoded as UTF-8. Throws ENVIRONMENT_UNSUPPORTED without a DOM.
|
|
108
|
+
*/
|
|
109
|
+
function download(data, filename, options) {
|
|
110
|
+
const g = globalThis;
|
|
111
|
+
const doc = g.document;
|
|
112
|
+
if (!doc?.body || typeof g.URL?.createObjectURL !== "function" || typeof g.Blob !== "function") throw new require_errors.EnvironmentError("ENVIRONMENT_UNSUPPORTED", "download() needs a browser DOM (document, URL.createObjectURL, Blob).", { details: { api: "document" } });
|
|
113
|
+
if (typeof filename !== "string" || filename.length === 0) throw new TypeError("download(): filename must be a non-empty string");
|
|
114
|
+
const Blob = g.Blob;
|
|
115
|
+
const isBlob = typeof data === "object" && data !== null && !(data instanceof Uint8Array);
|
|
116
|
+
let blob;
|
|
117
|
+
if (isBlob) {
|
|
118
|
+
const b = data;
|
|
119
|
+
blob = options?.mimeType && b.type !== options.mimeType ? new Blob([b], { type: options.mimeType }) : b;
|
|
120
|
+
} else blob = new Blob([data], { type: options?.mimeType ?? mimeFor(filename, data) });
|
|
121
|
+
const url = g.URL.createObjectURL(blob);
|
|
122
|
+
const a = doc.createElement("a");
|
|
123
|
+
a.href = url;
|
|
124
|
+
a.download = filename;
|
|
125
|
+
a.rel = "noopener";
|
|
126
|
+
a.style.display = "none";
|
|
127
|
+
doc.body.appendChild(a);
|
|
128
|
+
try {
|
|
129
|
+
a.click();
|
|
130
|
+
} finally {
|
|
131
|
+
a.remove();
|
|
132
|
+
const revoke = () => g.URL.revokeObjectURL(url);
|
|
133
|
+
if (typeof g.setTimeout === "function") g.setTimeout(revoke, DOWNLOAD_REVOKE_DELAY_MS);
|
|
134
|
+
else revoke();
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
function css(ctx, el, prop) {
|
|
138
|
+
if (!ctx.view) return "";
|
|
139
|
+
try {
|
|
140
|
+
return ctx.view.getComputedStyle(el).getPropertyValue(prop).trim();
|
|
141
|
+
} catch {
|
|
142
|
+
return "";
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
function inlineDisplayNone(el) {
|
|
146
|
+
const style = el.getAttribute("style");
|
|
147
|
+
return style !== null && /(?:^|;)\s*display\s*:\s*none\s*(?:!important\s*)?(?:;|$)/i.test(style);
|
|
148
|
+
}
|
|
149
|
+
function skipped(ctx, el) {
|
|
150
|
+
if (el.matches(ctx.ignore)) return true;
|
|
151
|
+
if (!ctx.skipHidden) return false;
|
|
152
|
+
if (el.hasAttribute("hidden") || inlineDisplayNone(el)) return true;
|
|
153
|
+
return ctx.computed && css(ctx, el, "display") === "none";
|
|
154
|
+
}
|
|
155
|
+
const SKIP_TEXT = /* @__PURE__ */ new Set([
|
|
156
|
+
"SCRIPT",
|
|
157
|
+
"STYLE",
|
|
158
|
+
"TEMPLATE",
|
|
159
|
+
"NOSCRIPT"
|
|
160
|
+
]);
|
|
161
|
+
/** Text of a cell: whitespace collapsed per line, <br> as a newline. */
|
|
162
|
+
function cellTextOf(el) {
|
|
163
|
+
const lines = [""];
|
|
164
|
+
let hasBreak = false;
|
|
165
|
+
const walk = (n) => {
|
|
166
|
+
if (n.nodeType === 3) {
|
|
167
|
+
lines[lines.length - 1] += n.textContent ?? "";
|
|
168
|
+
return;
|
|
169
|
+
}
|
|
170
|
+
if (!isElement(n)) return;
|
|
171
|
+
const tag = n.tagName.toUpperCase();
|
|
172
|
+
if (SKIP_TEXT.has(tag)) return;
|
|
173
|
+
if (tag === "BR") {
|
|
174
|
+
lines.push("");
|
|
175
|
+
hasBreak = true;
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
for (let i = 0; i < n.childNodes.length; i++) walk(n.childNodes[i]);
|
|
179
|
+
};
|
|
180
|
+
for (let i = 0; i < el.childNodes.length; i++) walk(el.childNodes[i]);
|
|
181
|
+
return {
|
|
182
|
+
text: lines.map((l) => l.replace(/[ \t\n\r\f ]+/g, " ").trim()).join("\n").replace(/^\n+|\n+$/g, ""),
|
|
183
|
+
hasBreak
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
const PLAIN_NUMBER = /^[+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?$/;
|
|
187
|
+
const GROUPED_NUMBER = /^[+-]?\d{1,3}(?:,\d{3})+(?:\.\d+)?$/;
|
|
188
|
+
const ISO_DATE = /^(\d{4})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{1,3})\d*)?)?(Z|[+-]\d{2}:?\d{2})?)?$/;
|
|
189
|
+
function parseNumber(s) {
|
|
190
|
+
const t = s.trim();
|
|
191
|
+
if (PLAIN_NUMBER.test(t)) return Number(t);
|
|
192
|
+
if (GROUPED_NUMBER.test(t)) return Number(t.replace(/,/g, ""));
|
|
193
|
+
}
|
|
194
|
+
function parseBoolean(s) {
|
|
195
|
+
const t = s.trim().toLowerCase();
|
|
196
|
+
if (t === "true" || t === "yes" || t === "1") return true;
|
|
197
|
+
if (t === "false" || t === "no" || t === "0") return false;
|
|
198
|
+
}
|
|
199
|
+
/** ISO 8601 date or date-time. Without a zone, the local wall-clock time (dateZone 'local'). */
|
|
200
|
+
function parseDate(s) {
|
|
201
|
+
const m = ISO_DATE.exec(s.trim());
|
|
202
|
+
if (!m) return void 0;
|
|
203
|
+
const [y, mo, d, h = "0", mi = "0", sec = "0", ms = "0", zone] = m.slice(1);
|
|
204
|
+
const parts = [
|
|
205
|
+
Number(y),
|
|
206
|
+
Number(mo) - 1,
|
|
207
|
+
Number(d),
|
|
208
|
+
Number(h),
|
|
209
|
+
Number(mi),
|
|
210
|
+
Number(sec),
|
|
211
|
+
Number(ms.padEnd(3, "0"))
|
|
212
|
+
];
|
|
213
|
+
let date;
|
|
214
|
+
if (zone) {
|
|
215
|
+
const off = zone === "Z" ? 0 : (zone[0] === "-" ? -1 : 1) * (Number(zone.slice(1, 3)) * 60 + Number(zone.slice(-2)));
|
|
216
|
+
date = /* @__PURE__ */ new Date(Date.UTC(...parts) - off * 6e4);
|
|
217
|
+
} else date = new Date(...parts);
|
|
218
|
+
const wall = zone ? new Date(Date.UTC(...parts)) : date;
|
|
219
|
+
const [month, day] = zone ? [wall.getUTCMonth(), wall.getUTCDate()] : [wall.getMonth(), wall.getDate()];
|
|
220
|
+
if (month !== parts[1] || day !== parts[2]) return void 0;
|
|
221
|
+
return Number.isFinite(date.getTime()) ? date : void 0;
|
|
222
|
+
}
|
|
223
|
+
function coerce(ctx, raw, type, ref) {
|
|
224
|
+
if (type === null || type === "" || type === "string") {
|
|
225
|
+
if (ctx.inferTypes) {
|
|
226
|
+
const n = PLAIN_NUMBER.test(raw.trim()) ? Number(raw.trim()) : void 0;
|
|
227
|
+
if (n !== void 0 && Number.isFinite(n)) return n;
|
|
228
|
+
const t = raw.trim().toLowerCase();
|
|
229
|
+
if (t === "true") return true;
|
|
230
|
+
if (t === "false") return false;
|
|
231
|
+
}
|
|
232
|
+
return raw;
|
|
233
|
+
}
|
|
234
|
+
const fail = () => {
|
|
235
|
+
ctx.warn({
|
|
236
|
+
code: "COERCION_FAILED",
|
|
237
|
+
message: `${ctx.sheet}!${ref}: ${JSON.stringify(raw)} is not a valid ${type}; kept as text.`,
|
|
238
|
+
sheet: ctx.sheet,
|
|
239
|
+
ref
|
|
240
|
+
});
|
|
241
|
+
return raw;
|
|
242
|
+
};
|
|
243
|
+
switch (type) {
|
|
244
|
+
case "number": {
|
|
245
|
+
const n = parseNumber(raw);
|
|
246
|
+
return n !== void 0 && Number.isFinite(n) ? n : fail();
|
|
247
|
+
}
|
|
248
|
+
case "boolean": return parseBoolean(raw) ?? fail();
|
|
249
|
+
case "date": return parseDate(raw) ?? fail();
|
|
250
|
+
default:
|
|
251
|
+
ctx.warn({
|
|
252
|
+
code: "COERCION_FAILED",
|
|
253
|
+
message: `${ctx.sheet}!${ref}: unknown data-type ${JSON.stringify(type)}; kept as text.`,
|
|
254
|
+
sheet: ctx.sheet,
|
|
255
|
+
ref
|
|
256
|
+
});
|
|
257
|
+
return raw;
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
/** The first non-transparent background of the cell, its row, section or table (what a reader sees). */
|
|
261
|
+
function backgroundOf(ctx, cell, table) {
|
|
262
|
+
for (let el = cell; el; el = el.parentElement) {
|
|
263
|
+
const c = cssColor(css(ctx, el, "background-color"));
|
|
264
|
+
if (c) return c;
|
|
265
|
+
if (el === table) break;
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
function computedStyle(ctx, el, table) {
|
|
269
|
+
const style = {};
|
|
270
|
+
const font = {};
|
|
271
|
+
const weight = css(ctx, el, "font-weight");
|
|
272
|
+
if (weight === "bold" || weight === "bolder" || Number(weight) >= 600) font.bold = true;
|
|
273
|
+
const fs = css(ctx, el, "font-style");
|
|
274
|
+
if (fs === "italic" || fs.startsWith("oblique")) font.italic = true;
|
|
275
|
+
const deco = `${css(ctx, el, "text-decoration-line")} ${css(ctx, el, "text-decoration")}`;
|
|
276
|
+
if (/\bunderline\b/.test(deco)) font.underline = true;
|
|
277
|
+
if (/\bline-through\b/.test(deco)) font.strike = true;
|
|
278
|
+
const color = cssColor(css(ctx, el, "color"));
|
|
279
|
+
if (color && color !== "000000") font.color = color;
|
|
280
|
+
if (Object.keys(font).length) style.font = font;
|
|
281
|
+
const bg = backgroundOf(ctx, el, table);
|
|
282
|
+
if (bg) style.fill = bg;
|
|
283
|
+
const alignment = {};
|
|
284
|
+
const ta = css(ctx, el, "text-align");
|
|
285
|
+
const h = /^(?:-webkit-|-internal-|-moz-)?center$/.test(ta) ? "center" : ta;
|
|
286
|
+
if (h === "left" || h === "right" || h === "center" || h === "justify") alignment.horizontal = h;
|
|
287
|
+
const va = css(ctx, el, "vertical-align");
|
|
288
|
+
if (va === "top" || va === "bottom") alignment.vertical = va;
|
|
289
|
+
const ws = css(ctx, el, "white-space");
|
|
290
|
+
if (ws === "pre-wrap" || ws === "pre-line" || ws === "break-spaces") alignment.wrapText = true;
|
|
291
|
+
if (Object.keys(alignment).length) style.alignment = alignment;
|
|
292
|
+
return Object.keys(style).length ? style : void 0;
|
|
293
|
+
}
|
|
294
|
+
function linkOf(ctx, cell, ref) {
|
|
295
|
+
const find = (n) => {
|
|
296
|
+
for (let i = 0; i < n.children.length; i++) {
|
|
297
|
+
const c = n.children[i];
|
|
298
|
+
if (c.tagName.toUpperCase() === "A" && c.hasAttribute("href")) return c;
|
|
299
|
+
const deeper = find(c);
|
|
300
|
+
if (deeper) return deeper;
|
|
301
|
+
}
|
|
302
|
+
};
|
|
303
|
+
const a = find(cell);
|
|
304
|
+
if (!a) return void 0;
|
|
305
|
+
const raw = a.getAttribute("href") ?? "";
|
|
306
|
+
if (raw.startsWith("#") || raw.trim() === "") return void 0;
|
|
307
|
+
const url = typeof a.href === "string" && a.href ? a.href : raw;
|
|
308
|
+
const scheme = /^([A-Za-z][A-Za-z0-9+.-]*):/.exec(url)?.[1]?.toLowerCase();
|
|
309
|
+
if (!scheme || !ctx.schemes.has(scheme)) {
|
|
310
|
+
ctx.warn({
|
|
311
|
+
code: "HYPERLINK_DROPPED",
|
|
312
|
+
message: `${ctx.sheet}!${ref}: link ${JSON.stringify(url)} dropped (scheme not allowed).`,
|
|
313
|
+
sheet: ctx.sheet,
|
|
314
|
+
ref
|
|
315
|
+
});
|
|
316
|
+
return;
|
|
317
|
+
}
|
|
318
|
+
return url;
|
|
319
|
+
}
|
|
320
|
+
/** Rows in reading order: <thead> rows, then <tbody> and bare <tr> rows, then <tfoot> rows. */
|
|
321
|
+
function collectRows(table, includeFooter) {
|
|
322
|
+
const head = [];
|
|
323
|
+
const body = [];
|
|
324
|
+
const foot = [];
|
|
325
|
+
const bare = [];
|
|
326
|
+
const trs = (section) => Array.from(section.children).filter((c) => c.tagName.toUpperCase() === "TR");
|
|
327
|
+
for (const child of Array.from(table.children)) {
|
|
328
|
+
const tag = child.tagName.toUpperCase();
|
|
329
|
+
if (tag === "THEAD") head.push(trs(child));
|
|
330
|
+
else if (tag === "TBODY") {
|
|
331
|
+
if (bare.length) body.push(bare.splice(0));
|
|
332
|
+
body.push(trs(child));
|
|
333
|
+
} else if (tag === "TFOOT") {
|
|
334
|
+
if (includeFooter) foot.push(trs(child));
|
|
335
|
+
} else if (tag === "TR") bare.push(child);
|
|
336
|
+
}
|
|
337
|
+
if (bare.length) body.push(bare);
|
|
338
|
+
const groups = [
|
|
339
|
+
...head,
|
|
340
|
+
...body,
|
|
341
|
+
...foot
|
|
342
|
+
];
|
|
343
|
+
const rows = groups.flat();
|
|
344
|
+
const sections = [];
|
|
345
|
+
groups.forEach((g, i) => g.forEach(() => sections.push(i)));
|
|
346
|
+
return {
|
|
347
|
+
rows,
|
|
348
|
+
sections
|
|
349
|
+
};
|
|
350
|
+
}
|
|
351
|
+
function intAttr(el, name, fallback, min, max) {
|
|
352
|
+
const v = el.getAttribute(name);
|
|
353
|
+
if (v === null) return fallback;
|
|
354
|
+
const n = Number.parseInt(v, 10);
|
|
355
|
+
if (!Number.isFinite(n)) return fallback;
|
|
356
|
+
return Math.min(max, Math.max(min, n));
|
|
357
|
+
}
|
|
358
|
+
/** Reads an HTML table into a Sheet: values, merges from colspan/rowspan, hints, links and (optionally) styles. */
|
|
359
|
+
function fromTable(table, options = {}) {
|
|
360
|
+
const t = table;
|
|
361
|
+
if (typeof t !== "object" || t === null || typeof t.tagName !== "string" || typeof t.matches !== "function") throw new require_errors.EnvironmentError("ENVIRONMENT_UNSUPPORTED", "fromTable() needs a DOM <table> element.", { details: { api: "HTMLTableElement" } });
|
|
362
|
+
if (t.tagName.toUpperCase() !== "TABLE") throw new TypeError(`fromTable(): expected a <table> element, got <${t.tagName.toLowerCase()}>`);
|
|
363
|
+
const name = options.name ?? "Sheet1";
|
|
364
|
+
const problem = require_sheet_names.validateSheetName(name);
|
|
365
|
+
if (problem) throw new require_errors.ValidationError("INVALID_SHEET_NAME", `fromTable(): sheet name ${JSON.stringify(name)} is invalid (${problem}).`, { details: {
|
|
366
|
+
sheet: name,
|
|
367
|
+
problem
|
|
368
|
+
} });
|
|
369
|
+
const ctx = {
|
|
370
|
+
view: t.ownerDocument?.defaultView ?? null,
|
|
371
|
+
computed: options.styles === "computed",
|
|
372
|
+
skipHidden: options.skipHidden !== false,
|
|
373
|
+
ignore: options.ignore ?? DEFAULT_IGNORE,
|
|
374
|
+
inferTypes: options.inferTypes === true,
|
|
375
|
+
links: options.links !== false,
|
|
376
|
+
schemes: options.hyperlinkSchemes === void 0 ? new Set(require_sheet_names.DEFAULT_HYPERLINK_SCHEMES) : require_sheet_names.hyperlinkSchemes(options.hyperlinkSchemes),
|
|
377
|
+
sheet: name,
|
|
378
|
+
warn: options.onWarning ?? (() => {})
|
|
379
|
+
};
|
|
380
|
+
const rtl = t.closest("[dir]")?.getAttribute("dir")?.toLowerCase() === "rtl" || ctx.computed && css(ctx, t, "direction") === "rtl";
|
|
381
|
+
const { rows: allRows, sections: allSections } = collectRows(t, options.includeFooter !== false);
|
|
382
|
+
const header = options.header ?? "thead";
|
|
383
|
+
const headerStyle = options.headerStyle ?? { font: { bold: true } };
|
|
384
|
+
const out = [];
|
|
385
|
+
const merges = [];
|
|
386
|
+
const occupied = [];
|
|
387
|
+
const occupy = (r, c) => {
|
|
388
|
+
(occupied[r] ??= [])[c] = true;
|
|
389
|
+
};
|
|
390
|
+
const kept = allRows.map((tr, i) => ({
|
|
391
|
+
tr,
|
|
392
|
+
section: allSections[i]
|
|
393
|
+
})).filter(({ tr }) => !skipped(ctx, tr));
|
|
394
|
+
const headerCount = header === "thead" ? kept.filter(({ tr }) => tr.parentElement?.tagName.toUpperCase() === "THEAD").length : header === false ? 0 : Math.max(0, Math.trunc(header));
|
|
395
|
+
let maxCol = -1;
|
|
396
|
+
kept.forEach(({ tr, section }, r) => {
|
|
397
|
+
const row = out[r] ??= [];
|
|
398
|
+
let c = 0;
|
|
399
|
+
for (const cell of Array.from(tr.children)) {
|
|
400
|
+
const tag = cell.tagName.toUpperCase();
|
|
401
|
+
if (tag !== "TD" && tag !== "TH") continue;
|
|
402
|
+
if (skipped(ctx, cell)) continue;
|
|
403
|
+
while (occupied[r]?.[c]) c++;
|
|
404
|
+
const colspan = intAttr(cell, "colspan", 1, 1, MAX_COLSPAN);
|
|
405
|
+
let rowspan = intAttr(cell, "rowspan", 1, 0, MAX_ROWSPAN);
|
|
406
|
+
if (rowspan === 0) {
|
|
407
|
+
let end = r;
|
|
408
|
+
while (end + 1 < kept.length && kept[end + 1].section === section) end++;
|
|
409
|
+
rowspan = end - r + 1;
|
|
410
|
+
}
|
|
411
|
+
rowspan = Math.min(rowspan, kept.length - r);
|
|
412
|
+
for (let dr = 0; dr < rowspan; dr++) for (let dc = 0; dc < colspan; dc++) occupy(r + dr, c + dc);
|
|
413
|
+
const ref = `${colName(c)}${r + 1}`;
|
|
414
|
+
if (colspan > 1 || rowspan > 1) merges.push(`${ref}:${colName(c + colspan - 1)}${r + rowspan}`);
|
|
415
|
+
const isHeader = r < headerCount;
|
|
416
|
+
const hooked = options.cell?.(cell, {
|
|
417
|
+
row: r,
|
|
418
|
+
col: c,
|
|
419
|
+
header: isHeader
|
|
420
|
+
});
|
|
421
|
+
if (hooked !== void 0) row[c] = hooked;
|
|
422
|
+
else {
|
|
423
|
+
const dataValue = cell.getAttribute("data-value");
|
|
424
|
+
const { text, hasBreak } = cellTextOf(cell);
|
|
425
|
+
const value = coerce(ctx, dataValue ?? text, cell.getAttribute("data-type"), ref);
|
|
426
|
+
const layers = [];
|
|
427
|
+
if (isHeader) layers.push(headerStyle);
|
|
428
|
+
if (ctx.computed) layers.push(computedStyle(ctx, cell, t));
|
|
429
|
+
if (hasBreak) layers.push({ alignment: { wrapText: true } });
|
|
430
|
+
const numFmt = cell.getAttribute("data-numfmt");
|
|
431
|
+
if (numFmt) layers.push({ numFmt: /^\d+$/.test(numFmt) ? Number(numFmt) : numFmt });
|
|
432
|
+
const style = layers.some(Boolean) ? require_sheet_names.mergeStyles(...layers) : void 0;
|
|
433
|
+
const hyperlink = ctx.links ? linkOf(ctx, cell, ref) : void 0;
|
|
434
|
+
row[c] = style === void 0 && hyperlink === void 0 ? value : {
|
|
435
|
+
value,
|
|
436
|
+
...style ? { style } : {},
|
|
437
|
+
...hyperlink ? { hyperlink } : {}
|
|
438
|
+
};
|
|
439
|
+
}
|
|
440
|
+
maxCol = Math.max(maxCol, c + colspan - 1);
|
|
441
|
+
c += colspan;
|
|
442
|
+
}
|
|
443
|
+
});
|
|
444
|
+
const sheet = {
|
|
445
|
+
name,
|
|
446
|
+
rows: out
|
|
447
|
+
};
|
|
448
|
+
if (merges.length) sheet.merges = merges;
|
|
449
|
+
const view = {};
|
|
450
|
+
if (rtl) view.rightToLeft = true;
|
|
451
|
+
if (options.freezeHeader && headerCount > 0) view.freeze = { rows: headerCount };
|
|
452
|
+
if (Object.keys(view).length) sheet.view = view;
|
|
453
|
+
if (options.autoFilter && headerCount > 0 && maxCol >= 0) sheet.autoFilter = `A${headerCount}:${colName(maxCol)}${Math.max(headerCount, out.length)}`;
|
|
454
|
+
if (options.autoWidth) sheet.colProps = autoWidths(out, typeof options.autoWidth === "object" ? options.autoWidth : {}).map((width) => ({ width }));
|
|
455
|
+
return sheet;
|
|
456
|
+
}
|
|
457
|
+
function colName(c) {
|
|
458
|
+
let s = "";
|
|
459
|
+
for (let n = c + 1; n > 0; n = Math.floor((n - 1) / 26)) s = String.fromCharCode(65 + (n - 1) % 26) + s;
|
|
460
|
+
return s;
|
|
461
|
+
}
|
|
462
|
+
exports.DOWNLOAD_REVOKE_DELAY_MS = DOWNLOAD_REVOKE_DELAY_MS;
|
|
463
|
+
exports.download = download;
|
|
464
|
+
exports.fromTable = fromTable;
|
package/dist/dom.d.cts
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* javascript-excel/dom: HTML table input and file download (docs/api.md §5.4).
|
|
3
|
+
*
|
|
4
|
+
* The only module that touches the DOM. Importing it never reads a global, so
|
|
5
|
+
* it is safe during server-side rendering; the DOM is used only inside the
|
|
6
|
+
* functions, and a table is read through its own window (iframes work).
|
|
7
|
+
*/
|
|
8
|
+
import { t as AutoWidthOptions } from "./auto-width-2oBzjeNG.cjs";
|
|
9
|
+
import { M as Sheet, P as Style, a as BlobType, f as CellInput, n as ExcelWarningCode, t as ExcelWarning } from "./warnings-C_12PT4t.cjs";
|
|
10
|
+
/** `HTMLTableElement` when the consumer has DOM types, else `object`. */
|
|
11
|
+
export type TableElement = typeof globalThis extends {
|
|
12
|
+
HTMLTableElement: {
|
|
13
|
+
prototype: infer T;
|
|
14
|
+
};
|
|
15
|
+
} ? T : object;
|
|
16
|
+
/** `HTMLTableCellElement` when the consumer has DOM types, else `object`. */
|
|
17
|
+
export type TableCellElement = typeof globalThis extends {
|
|
18
|
+
HTMLTableCellElement: {
|
|
19
|
+
prototype: infer T;
|
|
20
|
+
};
|
|
21
|
+
} ? T : object;
|
|
22
|
+
/** Options for `fromTable`. */
|
|
23
|
+
export interface FromTableOptions {
|
|
24
|
+
/** Sheet name, default 'Sheet1'. An invalid name throws INVALID_SHEET_NAME (§12 Q19). */
|
|
25
|
+
name?: string | undefined;
|
|
26
|
+
/** Header rows: 'thead' (default: the rows of <thead>), a fixed number of rows, or false. */
|
|
27
|
+
header?: "thead" | number | false | undefined;
|
|
28
|
+
/** Base style of header rows; default { font: { bold: true } }. */
|
|
29
|
+
headerStyle?: Style | undefined;
|
|
30
|
+
/** Include <tfoot> rows (last). Default true. */
|
|
31
|
+
includeFooter?: boolean | undefined;
|
|
32
|
+
/** Skip rows and cells with the `hidden` attribute or inline display:none (with styles: 'computed', also computed display:none). Default true. */
|
|
33
|
+
skipHidden?: boolean | undefined;
|
|
34
|
+
/** Rows and cells matching this selector are skipped. Default '[data-export-ignore]'. */
|
|
35
|
+
ignore?: string | undefined;
|
|
36
|
+
/** 'none' (default) or 'computed': map computed styles to cell styles. */
|
|
37
|
+
styles?: "none" | "computed" | undefined;
|
|
38
|
+
/** Turn plain numbers and TRUE/FALSE text into numbers and booleans. Default false. */
|
|
39
|
+
inferTypes?: boolean | undefined;
|
|
40
|
+
/** The first <a href> in a cell becomes its hyperlink. Default true. */
|
|
41
|
+
links?: boolean | undefined;
|
|
42
|
+
/** Link schemes kept; others are dropped with a HYPERLINK_DROPPED warning. Default ['http', 'https', 'mailto']. */
|
|
43
|
+
hyperlinkSchemes?: string[] | undefined;
|
|
44
|
+
/** Freeze the header rows. */
|
|
45
|
+
freezeHeader?: boolean | undefined;
|
|
46
|
+
/** Autofilter over the last header row and the body. Needs at least one header row. */
|
|
47
|
+
autoFilter?: boolean | undefined;
|
|
48
|
+
/** Estimate column widths from the text. */
|
|
49
|
+
autoWidth?: boolean | AutoWidthOptions | undefined;
|
|
50
|
+
/** Per-cell hook: return a CellInput to use instead of the default mapping, or undefined to keep it. */
|
|
51
|
+
cell?: ((el: TableCellElement, ctx: {
|
|
52
|
+
row: number;
|
|
53
|
+
col: number;
|
|
54
|
+
header: boolean;
|
|
55
|
+
}) => CellInput | undefined) | undefined;
|
|
56
|
+
/** Called for data problems that do not stop the conversion (COERCION_FAILED, HYPERLINK_DROPPED). */
|
|
57
|
+
onWarning?: ((w: ExcelWarning) => void) | undefined;
|
|
58
|
+
}
|
|
59
|
+
/** Options for `download`. */
|
|
60
|
+
export interface DownloadOptions {
|
|
61
|
+
/** Content type. Default from the data: a Blob keeps its own; otherwise from the file extension (.xlsx, .csv), else text/plain for strings and application/octet-stream for bytes. */
|
|
62
|
+
mimeType?: string | undefined;
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* How long the object URL stays valid after the click. Browsers start the
|
|
66
|
+
* download asynchronously, and Safari needs the URL for a while; 40 s is the
|
|
67
|
+
* delay FileSaver.js uses. Not measured here.
|
|
68
|
+
*/
|
|
69
|
+
export declare const DOWNLOAD_REVOKE_DELAY_MS = 4e4;
|
|
70
|
+
/**
|
|
71
|
+
* Saves data as a file in the browser: creates an object URL, clicks a
|
|
72
|
+
* temporary `<a download>` and revokes the URL after DOWNLOAD_REVOKE_DELAY_MS.
|
|
73
|
+
* A string is encoded as UTF-8. Throws ENVIRONMENT_UNSUPPORTED without a DOM.
|
|
74
|
+
*/
|
|
75
|
+
export declare function download(data: Uint8Array | BlobType | string, filename: string, options?: DownloadOptions): void;
|
|
76
|
+
/** Reads an HTML table into a Sheet: values, merges from colspan/rowspan, hints, links and (optionally) styles. */
|
|
77
|
+
export declare function fromTable(table: TableElement, options?: FromTableOptions): Sheet;
|
|
78
|
+
export type { AutoWidthOptions, BlobType, CellInput, ExcelWarning, ExcelWarningCode, Sheet, Style };
|
package/dist/dom.d.ts
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* javascript-excel/dom: HTML table input and file download (docs/api.md §5.4).
|
|
3
|
+
*
|
|
4
|
+
* The only module that touches the DOM. Importing it never reads a global, so
|
|
5
|
+
* it is safe during server-side rendering; the DOM is used only inside the
|
|
6
|
+
* functions, and a table is read through its own window (iframes work).
|
|
7
|
+
*/
|
|
8
|
+
import { t as AutoWidthOptions } from "./auto-width-CT-BihTW.js";
|
|
9
|
+
import { I as BlobType, j as Style, k as Sheet, l as CellInput, n as ExcelWarningCode, t as ExcelWarning } from "./warnings-DXJKe1lx.js";
|
|
10
|
+
/** `HTMLTableElement` when the consumer has DOM types, else `object`. */
|
|
11
|
+
export type TableElement = typeof globalThis extends {
|
|
12
|
+
HTMLTableElement: {
|
|
13
|
+
prototype: infer T;
|
|
14
|
+
};
|
|
15
|
+
} ? T : object;
|
|
16
|
+
/** `HTMLTableCellElement` when the consumer has DOM types, else `object`. */
|
|
17
|
+
export type TableCellElement = typeof globalThis extends {
|
|
18
|
+
HTMLTableCellElement: {
|
|
19
|
+
prototype: infer T;
|
|
20
|
+
};
|
|
21
|
+
} ? T : object;
|
|
22
|
+
/** Options for `fromTable`. */
|
|
23
|
+
export interface FromTableOptions {
|
|
24
|
+
/** Sheet name, default 'Sheet1'. An invalid name throws INVALID_SHEET_NAME (§12 Q19). */
|
|
25
|
+
name?: string | undefined;
|
|
26
|
+
/** Header rows: 'thead' (default: the rows of <thead>), a fixed number of rows, or false. */
|
|
27
|
+
header?: "thead" | number | false | undefined;
|
|
28
|
+
/** Base style of header rows; default { font: { bold: true } }. */
|
|
29
|
+
headerStyle?: Style | undefined;
|
|
30
|
+
/** Include <tfoot> rows (last). Default true. */
|
|
31
|
+
includeFooter?: boolean | undefined;
|
|
32
|
+
/** Skip rows and cells with the `hidden` attribute or inline display:none (with styles: 'computed', also computed display:none). Default true. */
|
|
33
|
+
skipHidden?: boolean | undefined;
|
|
34
|
+
/** Rows and cells matching this selector are skipped. Default '[data-export-ignore]'. */
|
|
35
|
+
ignore?: string | undefined;
|
|
36
|
+
/** 'none' (default) or 'computed': map computed styles to cell styles. */
|
|
37
|
+
styles?: "none" | "computed" | undefined;
|
|
38
|
+
/** Turn plain numbers and TRUE/FALSE text into numbers and booleans. Default false. */
|
|
39
|
+
inferTypes?: boolean | undefined;
|
|
40
|
+
/** The first <a href> in a cell becomes its hyperlink. Default true. */
|
|
41
|
+
links?: boolean | undefined;
|
|
42
|
+
/** Link schemes kept; others are dropped with a HYPERLINK_DROPPED warning. Default ['http', 'https', 'mailto']. */
|
|
43
|
+
hyperlinkSchemes?: string[] | undefined;
|
|
44
|
+
/** Freeze the header rows. */
|
|
45
|
+
freezeHeader?: boolean | undefined;
|
|
46
|
+
/** Autofilter over the last header row and the body. Needs at least one header row. */
|
|
47
|
+
autoFilter?: boolean | undefined;
|
|
48
|
+
/** Estimate column widths from the text. */
|
|
49
|
+
autoWidth?: boolean | AutoWidthOptions | undefined;
|
|
50
|
+
/** Per-cell hook: return a CellInput to use instead of the default mapping, or undefined to keep it. */
|
|
51
|
+
cell?: ((el: TableCellElement, ctx: {
|
|
52
|
+
row: number;
|
|
53
|
+
col: number;
|
|
54
|
+
header: boolean;
|
|
55
|
+
}) => CellInput | undefined) | undefined;
|
|
56
|
+
/** Called for data problems that do not stop the conversion (COERCION_FAILED, HYPERLINK_DROPPED). */
|
|
57
|
+
onWarning?: ((w: ExcelWarning) => void) | undefined;
|
|
58
|
+
}
|
|
59
|
+
/** Options for `download`. */
|
|
60
|
+
export interface DownloadOptions {
|
|
61
|
+
/** Content type. Default from the data: a Blob keeps its own; otherwise from the file extension (.xlsx, .csv), else text/plain for strings and application/octet-stream for bytes. */
|
|
62
|
+
mimeType?: string | undefined;
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* How long the object URL stays valid after the click. Browsers start the
|
|
66
|
+
* download asynchronously, and Safari needs the URL for a while; 40 s is the
|
|
67
|
+
* delay FileSaver.js uses. Not measured here.
|
|
68
|
+
*/
|
|
69
|
+
export declare const DOWNLOAD_REVOKE_DELAY_MS = 4e4;
|
|
70
|
+
/**
|
|
71
|
+
* Saves data as a file in the browser: creates an object URL, clicks a
|
|
72
|
+
* temporary `<a download>` and revokes the URL after DOWNLOAD_REVOKE_DELAY_MS.
|
|
73
|
+
* A string is encoded as UTF-8. Throws ENVIRONMENT_UNSUPPORTED without a DOM.
|
|
74
|
+
*/
|
|
75
|
+
export declare function download(data: Uint8Array | BlobType | string, filename: string, options?: DownloadOptions): void;
|
|
76
|
+
/** Reads an HTML table into a Sheet: values, merges from colspan/rowspan, hints, links and (optionally) styles. */
|
|
77
|
+
export declare function fromTable(table: TableElement, options?: FromTableOptions): Sheet;
|
|
78
|
+
export type { AutoWidthOptions, BlobType, CellInput, ExcelWarning, ExcelWarningCode, Sheet, Style };
|