@js-ak/excel-toolbox 1.4.0 → 1.5.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.
Files changed (42) hide show
  1. package/build/cjs/lib/template/index.js +1 -0
  2. package/build/cjs/lib/template/memory-write-stream.js +17 -0
  3. package/build/cjs/lib/template/template-fs.js +4 -223
  4. package/build/cjs/lib/template/template-memory.js +531 -0
  5. package/build/cjs/lib/template/utils/extract-xml-declaration.js +1 -1
  6. package/build/cjs/lib/template/utils/get-max-row-number.js +1 -1
  7. package/build/cjs/lib/template/utils/index.js +4 -0
  8. package/build/cjs/lib/template/utils/prepare-row-to-cells.js +13 -0
  9. package/build/cjs/lib/template/utils/process-merge-cells.js +40 -0
  10. package/build/cjs/lib/template/utils/process-merge-finalize.js +51 -0
  11. package/build/cjs/lib/template/utils/process-rows.js +160 -0
  12. package/build/cjs/lib/template/utils/process-shared-strings.js +45 -0
  13. package/build/cjs/lib/template/utils/to-excel-column-object.js +2 -10
  14. package/build/cjs/lib/template/utils/validate-worksheet-xml.js +65 -51
  15. package/build/cjs/lib/template/utils/write-rows-to-stream.js +15 -10
  16. package/build/esm/lib/template/index.js +1 -0
  17. package/build/esm/lib/template/memory-write-stream.js +13 -0
  18. package/build/esm/lib/template/template-fs.js +4 -223
  19. package/build/esm/lib/template/template-memory.js +494 -0
  20. package/build/esm/lib/template/utils/extract-xml-declaration.js +1 -1
  21. package/build/esm/lib/template/utils/get-max-row-number.js +1 -1
  22. package/build/esm/lib/template/utils/index.js +4 -0
  23. package/build/esm/lib/template/utils/prepare-row-to-cells.js +10 -0
  24. package/build/esm/lib/template/utils/process-merge-cells.js +37 -0
  25. package/build/esm/lib/template/utils/process-merge-finalize.js +48 -0
  26. package/build/esm/lib/template/utils/process-rows.js +157 -0
  27. package/build/esm/lib/template/utils/process-shared-strings.js +42 -0
  28. package/build/esm/lib/template/utils/to-excel-column-object.js +2 -10
  29. package/build/esm/lib/template/utils/validate-worksheet-xml.js +65 -51
  30. package/build/esm/lib/template/utils/write-rows-to-stream.js +15 -10
  31. package/build/types/lib/template/index.d.ts +1 -0
  32. package/build/types/lib/template/memory-write-stream.d.ts +6 -0
  33. package/build/types/lib/template/template-memory.d.ts +85 -0
  34. package/build/types/lib/template/utils/index.d.ts +4 -0
  35. package/build/types/lib/template/utils/prepare-row-to-cells.d.ts +1 -0
  36. package/build/types/lib/template/utils/process-merge-cells.d.ts +20 -0
  37. package/build/types/lib/template/utils/process-merge-finalize.d.ts +38 -0
  38. package/build/types/lib/template/utils/process-rows.d.ts +31 -0
  39. package/build/types/lib/template/utils/process-shared-strings.d.ts +20 -0
  40. package/build/types/lib/template/utils/validate-worksheet-xml.d.ts +16 -0
  41. package/build/types/lib/template/utils/write-rows-to-stream.d.ts +6 -2
  42. package/package.json +5 -3
@@ -0,0 +1,531 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.TemplateMemory = void 0;
37
+ const fs = __importStar(require("node:fs/promises"));
38
+ const Xml = __importStar(require("../xml/index.js"));
39
+ const Zip = __importStar(require("../zip/index.js"));
40
+ const Utils = __importStar(require("./utils/index.js"));
41
+ const memory_write_stream_js_1 = require("./memory-write-stream.js");
42
+ /**
43
+ * A class for manipulating Excel templates by extracting, modifying, and repacking Excel files.
44
+ *
45
+ * @experimental This API is experimental and might change in future versions.
46
+ */
47
+ class TemplateMemory {
48
+ files;
49
+ /**
50
+ * Flag indicating whether this template instance has been destroyed.
51
+ * @type {boolean}
52
+ */
53
+ destroyed = false;
54
+ /**
55
+ * Flag indicating whether this template instance is currently being processed.
56
+ * @type {boolean}
57
+ */
58
+ #isProcessing = false;
59
+ constructor(files) {
60
+ this.files = files;
61
+ }
62
+ /**
63
+ * Ensures that this Template instance has not been destroyed.
64
+ * @private
65
+ * @throws {Error} If the template instance has already been destroyed.
66
+ * @experimental This API is experimental and might change in future versions.
67
+ */
68
+ #ensureNotDestroyed() {
69
+ if (this.destroyed) {
70
+ throw new Error("This Template instance has already been saved and destroyed.");
71
+ }
72
+ }
73
+ /**
74
+ * Ensures that this Template instance is not currently being processed.
75
+ * @throws {Error} If the template instance is currently being processed.
76
+ * @experimental This API is experimental and might change in future versions.
77
+ */
78
+ #ensureNotProcessing() {
79
+ if (this.#isProcessing) {
80
+ throw new Error("This Template instance is currently being processed.");
81
+ }
82
+ }
83
+ /**
84
+ * Expand table rows in the given sheet and shared strings XML.
85
+ *
86
+ * @param {string} sheetXml - The XML content of the sheet.
87
+ * @param {string} sharedStringsXml - The XML content of the shared strings.
88
+ * @param {Record<string, unknown>} replacements - An object containing replacement values.
89
+ *
90
+ * @returns {Object} An object with two properties:
91
+ * - sheet: The expanded sheet XML.
92
+ * - shared: The expanded shared strings XML.
93
+ * @experimental This API is experimental and might change in future versions.
94
+ */
95
+ #expandTableRows(sheetXml, sharedStringsXml, replacements) {
96
+ const { initialMergeCells, mergeCellMatches, modifiedXml, } = Utils.processMergeCells(sheetXml);
97
+ const { sharedIndexMap, sharedStrings, sharedStringsHeader, sheetMergeCells, } = Utils.processSharedStrings(sharedStringsXml);
98
+ const { lastIndex, resultRows, rowShift } = Utils.processRows({
99
+ mergeCellMatches,
100
+ replacements,
101
+ sharedIndexMap,
102
+ sharedStrings,
103
+ sheetMergeCells,
104
+ sheetXml: modifiedXml,
105
+ });
106
+ return Utils.processMergeFinalize({
107
+ initialMergeCells,
108
+ lastIndex,
109
+ mergeCellMatches,
110
+ resultRows,
111
+ rowShift,
112
+ sharedStrings,
113
+ sharedStringsHeader,
114
+ sheetMergeCells,
115
+ sheetXml: modifiedXml,
116
+ });
117
+ }
118
+ #getXml(fileKey) {
119
+ if (!this.files[fileKey]) {
120
+ throw new Error(`${fileKey} not found`);
121
+ }
122
+ return Xml.extractXmlFromSheet(this.files[fileKey]);
123
+ }
124
+ /**
125
+ * Get the path of the sheet with the given name inside the workbook.
126
+ * @param sheetName The name of the sheet to find.
127
+ * @returns The path of the sheet inside the workbook.
128
+ * @throws {Error} If the sheet is not found.
129
+ */
130
+ async #getSheetPath(sheetName) {
131
+ // Read XML workbook to find sheet name and path
132
+ const workbookXml = this.#getXml("xl/workbook.xml");
133
+ const sheetMatch = workbookXml.match(new RegExp(`<sheet[^>]+name="${sheetName}"[^>]+r:id="([^"]+)"[^>]*/>`));
134
+ if (!sheetMatch)
135
+ throw new Error(`Sheet "${sheetName}" not found`);
136
+ const rId = sheetMatch[1];
137
+ const relsXml = this.#getXml("xl/_rels/workbook.xml.rels");
138
+ const relMatch = relsXml.match(new RegExp(`<Relationship[^>]+Id="${rId}"[^>]+Target="([^"]+)"[^>]*/>`));
139
+ if (!relMatch)
140
+ throw new Error(`Relationship "${rId}" not found`);
141
+ return "xl/" + relMatch[1].replace(/^\/?xl\//, "");
142
+ }
143
+ /**
144
+ * Replaces the contents of a file in the template.
145
+ *
146
+ * @param {string} key - The Excel path of the file to replace.
147
+ * @param {Buffer|string} content - The new content.
148
+ * @returns {Promise<void>}
149
+ * @throws {Error} If the template instance has been destroyed.
150
+ * @throws {Error} If the file does not exist in the template.
151
+ * @experimental This API is experimental and might change in future versions.
152
+ */
153
+ async #set(key, content) {
154
+ this.files[key] = content;
155
+ }
156
+ async #substitute(sheetName, replacements) {
157
+ const sharedStringsPath = "xl/sharedStrings.xml";
158
+ const sheetPath = await this.#getSheetPath(sheetName);
159
+ let sharedStringsContent = "";
160
+ let sheetContent = "";
161
+ if (this.files[sharedStringsPath]) {
162
+ sharedStringsContent = this.#getXml(sharedStringsPath);
163
+ }
164
+ if (this.files[sheetPath]) {
165
+ sheetContent = this.#getXml(sheetPath);
166
+ const TABLE_REGEX = /\$\{table:([a-zA-Z0-9_]+)\.([a-zA-Z0-9_]+)\}/g;
167
+ const hasTablePlaceholders = TABLE_REGEX.test(sharedStringsContent) || TABLE_REGEX.test(sheetContent);
168
+ if (hasTablePlaceholders) {
169
+ const result = this.#expandTableRows(sheetContent, sharedStringsContent, replacements);
170
+ sheetContent = result.sheet;
171
+ sharedStringsContent = result.shared;
172
+ }
173
+ }
174
+ if (this.files[sharedStringsPath]) {
175
+ sharedStringsContent = Utils.applyReplacements(sharedStringsContent, replacements);
176
+ await this.#set(sharedStringsPath, Buffer.from(sharedStringsContent));
177
+ }
178
+ if (this.files[sheetPath]) {
179
+ sheetContent = Utils.applyReplacements(sheetContent, replacements);
180
+ await this.#set(sheetPath, Buffer.from(sheetContent));
181
+ }
182
+ }
183
+ /**
184
+ * Copies a sheet from the template to a new name.
185
+ *
186
+ * @param {string} sourceName - The name of the sheet to copy.
187
+ * @param {string} newName - The new name for the sheet.
188
+ * @returns {Promise<void>}
189
+ * @throws {Error} If the sheet with the source name does not exist.
190
+ * @throws {Error} If a sheet with the new name already exists.
191
+ * @experimental This API is experimental and might change in future versions.
192
+ */
193
+ async copySheet(sourceName, newName) {
194
+ this.#ensureNotProcessing();
195
+ this.#ensureNotDestroyed();
196
+ this.#isProcessing = true;
197
+ try {
198
+ // Read workbook.xml and find the source sheet
199
+ const workbookXmlPath = "xl/workbook.xml";
200
+ const workbookXml = this.#getXml(workbookXmlPath);
201
+ // Find the source sheet
202
+ const sheetRegex = new RegExp(`<sheet[^>]+name="${sourceName}"[^>]+r:id="([^"]+)"[^>]*/>`);
203
+ const sheetMatch = workbookXml.match(sheetRegex);
204
+ if (!sheetMatch)
205
+ throw new Error(`Sheet "${sourceName}" not found`);
206
+ const sourceRId = sheetMatch[1];
207
+ // Check if a sheet with the new name already exists
208
+ if (new RegExp(`<sheet[^>]+name="${newName}"`).test(workbookXml)) {
209
+ throw new Error(`Sheet "${newName}" already exists`);
210
+ }
211
+ // Read workbook.rels
212
+ // Find the source sheet path by rId
213
+ const relsXmlPath = "xl/_rels/workbook.xml.rels";
214
+ const relsXml = this.#getXml(relsXmlPath);
215
+ const relRegex = new RegExp(`<Relationship[^>]+Id="${sourceRId}"[^>]+Target="([^"]+)"[^>]*/>`);
216
+ const relMatch = relsXml.match(relRegex);
217
+ if (!relMatch)
218
+ throw new Error(`Relationship "${sourceRId}" not found`);
219
+ const sourceTarget = relMatch[1]; // sheetN.xml
220
+ if (!sourceTarget)
221
+ throw new Error(`Relationship "${sourceRId}" not found`);
222
+ const sourceSheetPath = "xl/" + sourceTarget.replace(/^\/?.*xl\//, "");
223
+ // Get the index of the new sheet
224
+ const sheetNumbers = Array.from(Object.keys(this.files))
225
+ .map((key) => key.match(/^xl\/worksheets\/sheet(\d+)\.xml$/))
226
+ .filter(Boolean)
227
+ .map((match) => parseInt(match[1], 10));
228
+ const nextSheetIndex = sheetNumbers.length > 0 ? Math.max(...sheetNumbers) + 1 : 1;
229
+ const newSheetFilename = `sheet${nextSheetIndex}.xml`;
230
+ const newSheetPath = `xl/worksheets/${newSheetFilename}`;
231
+ const newTarget = `worksheets/${newSheetFilename}`;
232
+ // Generate a unique rId
233
+ const usedRIds = [...relsXml.matchAll(/Id="(rId\d+)"/g)].map(m => m[1]);
234
+ let nextRIdNum = 1;
235
+ while (usedRIds.includes(`rId${nextRIdNum}`))
236
+ nextRIdNum++;
237
+ const newRId = `rId${nextRIdNum}`;
238
+ // Copy the source sheet file
239
+ const sheetContent = this.files[sourceSheetPath];
240
+ if (!sheetContent) {
241
+ throw new Error(`Sheet "${sourceSheetPath}" not found`);
242
+ }
243
+ function copyBuffer(source) {
244
+ const target = Buffer.alloc(source.length);
245
+ source.copy(target);
246
+ return target;
247
+ }
248
+ await this.#set(newSheetPath, copyBuffer(sheetContent));
249
+ // Update workbook.xml
250
+ const updatedWorkbookXml = workbookXml.replace("</sheets>", `<sheet name="${newName}" sheetId="${nextSheetIndex}" r:id="${newRId}"/></sheets>`);
251
+ await this.#set(workbookXmlPath, Buffer.from(updatedWorkbookXml));
252
+ // Update workbook.xml.rels
253
+ const updatedRelsXml = relsXml.replace("</Relationships>", `<Relationship Id="${newRId}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="${newTarget}"/></Relationships>`);
254
+ await this.#set(relsXmlPath, Buffer.from(updatedRelsXml));
255
+ // Read [Content_Types].xml
256
+ // Update [Content_Types].xml
257
+ const contentTypesPath = "[Content_Types].xml";
258
+ const contentTypesXml = this.#getXml(contentTypesPath);
259
+ const overrideTag = `<Override PartName="/xl/worksheets/${newSheetFilename}" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>`;
260
+ const updatedContentTypesXml = contentTypesXml.replace("</Types>", overrideTag + "</Types>");
261
+ await this.#set(contentTypesPath, Buffer.from(updatedContentTypesXml));
262
+ }
263
+ finally {
264
+ this.#isProcessing = false;
265
+ }
266
+ }
267
+ /**
268
+ * Replaces placeholders in the given sheet with values from the replacements map.
269
+ *
270
+ * The function searches for placeholders in the format `${key}` within the sheet
271
+ * content, where `key` corresponds to a path in the replacements object.
272
+ * If a value is found for the key, it replaces the placeholder with the value.
273
+ * If no value is found, the original placeholder remains unchanged.
274
+ *
275
+ * @param sheetName - The name of the sheet to be replaced.
276
+ * @param replacements - An object where keys represent placeholder paths and values are the replacements.
277
+ * @returns A promise that resolves when the substitution is complete.
278
+ */
279
+ substitute(sheetName, replacements) {
280
+ this.#ensureNotProcessing();
281
+ this.#ensureNotDestroyed();
282
+ this.#isProcessing = true;
283
+ try {
284
+ return this.#substitute(sheetName, replacements);
285
+ }
286
+ finally {
287
+ this.#isProcessing = false;
288
+ }
289
+ }
290
+ /**
291
+ * Inserts rows into a specific sheet in the template.
292
+ *
293
+ * @param {Object} data - The data for row insertion.
294
+ * @param {string} data.sheetName - The name of the sheet to insert rows into.
295
+ * @param {number} [data.startRowNumber] - The row number to start inserting from.
296
+ * @param {unknown[][]} data.rows - The rows to insert.
297
+ * @returns {Promise<void>}
298
+ * @throws {Error} If the template instance has been destroyed.
299
+ * @throws {Error} If the sheet does not exist.
300
+ * @throws {Error} If the row number is out of range.
301
+ * @throws {Error} If a column is out of range.
302
+ * @experimental This API is experimental and might change in future versions.
303
+ */
304
+ async insertRows(data) {
305
+ this.#ensureNotProcessing();
306
+ this.#ensureNotDestroyed();
307
+ this.#isProcessing = true;
308
+ try {
309
+ const { rows, sheetName, startRowNumber } = data;
310
+ const preparedRows = rows.map(row => Utils.toExcelColumnObject(row));
311
+ // Validation
312
+ Utils.checkStartRow(startRowNumber);
313
+ Utils.checkRows(preparedRows);
314
+ // Find the sheet
315
+ const workbookXml = this.#getXml("xl/workbook.xml");
316
+ const sheetMatch = workbookXml.match(new RegExp(`<sheet[^>]+name="${sheetName}"[^>]+r:id="([^"]+)"[^>]*/>`));
317
+ if (!sheetMatch || !sheetMatch[1]) {
318
+ throw new Error(`Sheet "${sheetName}" not found`);
319
+ }
320
+ const rId = sheetMatch[1];
321
+ const relsXml = this.#getXml("xl/_rels/workbook.xml.rels");
322
+ const relMatch = relsXml.match(new RegExp(`<Relationship[^>]+Id="${rId}"[^>]+Target="([^"]+)"[^>]*/>`));
323
+ if (!relMatch || !relMatch[1]) {
324
+ throw new Error(`Relationship "${rId}" not found`);
325
+ }
326
+ const sheetPath = "xl/" + relMatch[1].replace(/^\/?xl\//, "");
327
+ const sheetXml = this.#getXml(sheetPath);
328
+ let nextRow = 0;
329
+ if (!startRowNumber) {
330
+ // Find the last row
331
+ let lastRowNumber = 0;
332
+ const rowMatches = [...sheetXml.matchAll(/<row[^>]+r="(\d+)"[^>]*>/g)];
333
+ if (rowMatches.length > 0) {
334
+ lastRowNumber = Math.max(...rowMatches.map((m) => parseInt(m[1], 10)));
335
+ }
336
+ nextRow = lastRowNumber + 1;
337
+ }
338
+ else {
339
+ nextRow = startRowNumber;
340
+ }
341
+ // Generate XML for all rows
342
+ const rowsXml = preparedRows.map((cells, i) => {
343
+ const rowNumber = nextRow + i;
344
+ const cellTags = Object.entries(cells).map(([col, value]) => {
345
+ const colUpper = col.toUpperCase();
346
+ const ref = `${colUpper}${rowNumber}`;
347
+ return `<c r="${ref}" t="inlineStr"><is><t>${Utils.escapeXml(value)}</t></is></c>`;
348
+ }).join("");
349
+ return `<row r="${rowNumber}">${cellTags}</row>`;
350
+ }).join("");
351
+ let updatedXml;
352
+ if (/<sheetData\s*\/>/.test(sheetXml)) {
353
+ updatedXml = sheetXml.replace(/<sheetData\s*\/>/, `<sheetData>${rowsXml}</sheetData>`);
354
+ }
355
+ else if (/<sheetData>([\s\S]*?)<\/sheetData>/.test(sheetXml)) {
356
+ updatedXml = sheetXml.replace(/<\/sheetData>/, `${rowsXml}</sheetData>`);
357
+ }
358
+ else {
359
+ updatedXml = sheetXml.replace(/<worksheet[^>]*>/, (match) => `${match}<sheetData>${rowsXml}</sheetData>`);
360
+ }
361
+ await this.#set(sheetPath, Buffer.from(updatedXml));
362
+ }
363
+ finally {
364
+ this.#isProcessing = false;
365
+ }
366
+ }
367
+ async insertRowsStream(data) {
368
+ this.#ensureNotProcessing();
369
+ this.#ensureNotDestroyed();
370
+ this.#isProcessing = true;
371
+ try {
372
+ const { rows, sheetName, startRowNumber } = data;
373
+ if (!sheetName)
374
+ throw new Error("Sheet name is required");
375
+ const workbookXml = this.#getXml("xl/workbook.xml");
376
+ const sheetMatch = workbookXml.match(new RegExp(`<sheet[^>]+name="${sheetName}"[^>]+r:id="([^"]+)"[^>]*/>`));
377
+ if (!sheetMatch)
378
+ throw new Error(`Sheet "${sheetName}" not found`);
379
+ const rId = sheetMatch[1];
380
+ const relsXml = this.#getXml("xl/_rels/workbook.xml.rels");
381
+ const relMatch = relsXml.match(new RegExp(`<Relationship[^>]+Id="${rId}"[^>]+Target="([^"]+)"[^>]*/>`));
382
+ if (!relMatch || !relMatch[1])
383
+ throw new Error(`Relationship "${rId}" not found`);
384
+ const sheetPath = "xl/" + relMatch[1].replace(/^\/?xl\//, "");
385
+ const sheetXml = this.#getXml(sheetPath);
386
+ const output = new memory_write_stream_js_1.MemoryWriteStream();
387
+ let inserted = false;
388
+ // --- Case 1: <sheetData>...</sheetData> on one line ---
389
+ const singleLineMatch = sheetXml.match(/(<sheetData[^>]*>)(.*)(<\/sheetData>)/);
390
+ if (!inserted && singleLineMatch) {
391
+ const maxRowNumber = startRowNumber ?? Utils.getMaxRowNumber(sheetXml);
392
+ const openTag = singleLineMatch[1];
393
+ const innerRows = singleLineMatch[2].trim();
394
+ const closeTag = singleLineMatch[3];
395
+ const innerRowsMap = Utils.parseRows(innerRows);
396
+ output.write(sheetXml.slice(0, singleLineMatch.index));
397
+ output.write(openTag);
398
+ if (innerRows) {
399
+ if (startRowNumber) {
400
+ const filtered = Utils.getRowsBelow(innerRowsMap, startRowNumber);
401
+ if (filtered)
402
+ output.write(filtered);
403
+ }
404
+ else {
405
+ output.write(innerRows);
406
+ }
407
+ }
408
+ const { rowNumber: actualRowNumber } = await Utils.writeRowsToStream(output, rows, maxRowNumber);
409
+ if (innerRows) {
410
+ const filtered = Utils.getRowsAbove(innerRowsMap, actualRowNumber);
411
+ if (filtered)
412
+ output.write(filtered);
413
+ }
414
+ output.write(closeTag);
415
+ output.write(sheetXml.slice(singleLineMatch.index + singleLineMatch[0].length));
416
+ inserted = true;
417
+ }
418
+ // --- Case 2: <sheetData/> ---
419
+ if (!inserted && /<sheetData\s*\/>/.test(sheetXml)) {
420
+ const maxRowNumber = startRowNumber ?? Utils.getMaxRowNumber(sheetXml);
421
+ const match = sheetXml.match(/<sheetData\s*\/>/);
422
+ const matchIndex = match.index;
423
+ output.write(sheetXml.slice(0, matchIndex));
424
+ output.write("<sheetData>");
425
+ await Utils.writeRowsToStream(output, rows, maxRowNumber);
426
+ output.write("</sheetData>");
427
+ output.write(sheetXml.slice(matchIndex + match[0].length));
428
+ inserted = true;
429
+ }
430
+ // --- Case 3: Multiline <sheetData> ---
431
+ if (!inserted && sheetXml.includes("<sheetData")) {
432
+ const openTagMatch = sheetXml.match(/<sheetData[^>]*>/);
433
+ const closeTag = "</sheetData>";
434
+ if (!openTagMatch)
435
+ throw new Error("Invalid sheetData structure");
436
+ const openTag = openTagMatch[0];
437
+ const openIdx = sheetXml.indexOf(openTag);
438
+ const closeIdx = sheetXml.lastIndexOf(closeTag);
439
+ if (closeIdx === -1)
440
+ throw new Error("Missing </sheetData>");
441
+ const beforeRows = sheetXml.slice(0, openIdx + openTag.length);
442
+ const innerRows = sheetXml.slice(openIdx + openTag.length, closeIdx).trim();
443
+ const afterRows = sheetXml.slice(closeIdx + closeTag.length);
444
+ const innerRowsMap = Utils.parseRows(innerRows);
445
+ output.write(beforeRows);
446
+ if (innerRows) {
447
+ if (startRowNumber) {
448
+ const filtered = Utils.getRowsBelow(innerRowsMap, startRowNumber);
449
+ if (filtered)
450
+ output.write(filtered);
451
+ }
452
+ else {
453
+ output.write(innerRows);
454
+ }
455
+ }
456
+ const { rowNumber: actualRowNumber } = await Utils.writeRowsToStream(output, rows, Utils.getMaxRowNumber(innerRows));
457
+ if (innerRows) {
458
+ const filtered = Utils.getRowsAbove(innerRowsMap, actualRowNumber);
459
+ if (filtered)
460
+ output.write(filtered);
461
+ }
462
+ output.write(closeTag);
463
+ output.write(afterRows);
464
+ inserted = true;
465
+ }
466
+ if (!inserted)
467
+ throw new Error("Failed to locate <sheetData> for insertion");
468
+ // ← теперь мы не собираем строку, а собираем Buffer
469
+ this.files[sheetPath] = output.toBuffer();
470
+ }
471
+ finally {
472
+ this.#isProcessing = false;
473
+ }
474
+ }
475
+ /**
476
+ * Saves the modified Excel template to a buffer.
477
+ *
478
+ * @returns {Promise<Buffer>} The modified Excel template as a buffer.
479
+ * @throws {Error} If the template instance has been destroyed.
480
+ * @experimental This API is experimental and might change in future versions.
481
+ */
482
+ async save() {
483
+ this.#ensureNotProcessing();
484
+ this.#ensureNotDestroyed();
485
+ this.#isProcessing = true;
486
+ try {
487
+ const zipBuffer = await Zip.create(this.files);
488
+ this.destroyed = true;
489
+ // Очистка всех буферов
490
+ for (const key in this.files) {
491
+ if (this.files.hasOwnProperty(key)) {
492
+ this.files[key] = Buffer.alloc(0); // Заменяем на пустой буфер
493
+ }
494
+ }
495
+ return zipBuffer;
496
+ }
497
+ finally {
498
+ this.#isProcessing = false;
499
+ }
500
+ }
501
+ /**
502
+ * Replaces the contents of a file in the template.
503
+ *
504
+ * @param {string} key - The Excel path of the file to replace.
505
+ * @param {Buffer|string} content - The new content.
506
+ * @returns {Promise<void>}
507
+ * @throws {Error} If the template instance has been destroyed.
508
+ * @throws {Error} If the file does not exist in the template.
509
+ * @experimental This API is experimental and might change in future versions.
510
+ */
511
+ async set(key, content) {
512
+ this.#ensureNotProcessing();
513
+ this.#ensureNotDestroyed();
514
+ this.#isProcessing = true;
515
+ try {
516
+ await this.#set(key, content);
517
+ }
518
+ finally {
519
+ this.#isProcessing = false;
520
+ }
521
+ }
522
+ static async from(data) {
523
+ const { source } = data;
524
+ const buffer = typeof source === "string"
525
+ ? await fs.readFile(source)
526
+ : source;
527
+ const files = await Zip.read(buffer);
528
+ return new TemplateMemory(files);
529
+ }
530
+ }
531
+ exports.TemplateMemory = TemplateMemory;
@@ -17,6 +17,6 @@ exports.extractXmlDeclaration = extractXmlDeclaration;
17
17
  function extractXmlDeclaration(xmlString) {
18
18
  // const declarationRegex = /^<\?xml\s+[^?]+\?>/;
19
19
  const declarationRegex = /^<\?xml\s+version\s*=\s*["'][^"']+["'](\s+(encoding|standalone)\s*=\s*["'][^"']+["'])*\s*\?>/;
20
- const match = xmlString.match(declarationRegex);
20
+ const match = xmlString.trim().match(declarationRegex);
21
21
  return match ? match[0] : null;
22
22
  }
@@ -9,7 +9,7 @@ exports.getMaxRowNumber = getMaxRowNumber;
9
9
  */
10
10
  function getMaxRowNumber(line) {
11
11
  let result = 1;
12
- const rowMatches = [...line.matchAll(/<row[^>]+r="(\d+)"[^>]*>/g)];
12
+ const rowMatches = [...line.matchAll(/<row[^>]+r="(\d+)"[^>]*>/gi)];
13
13
  for (const match of rowMatches) {
14
14
  const rowNum = parseInt(match[1], 10);
15
15
  if (rowNum >= result) {
@@ -26,6 +26,10 @@ __exportStar(require("./get-max-row-number.js"), exports);
26
26
  __exportStar(require("./get-rows-above.js"), exports);
27
27
  __exportStar(require("./get-rows-below.js"), exports);
28
28
  __exportStar(require("./parse-rows.js"), exports);
29
+ __exportStar(require("./process-merge-cells.js"), exports);
30
+ __exportStar(require("./process-merge-finalize.js"), exports);
31
+ __exportStar(require("./process-rows.js"), exports);
32
+ __exportStar(require("./process-shared-strings.js"), exports);
29
33
  __exportStar(require("./to-excel-column-object.js"), exports);
30
34
  __exportStar(require("./update-dimension.js"), exports);
31
35
  __exportStar(require("./validate-worksheet-xml.js"), exports);
@@ -0,0 +1,13 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.prepareRowToCells = prepareRowToCells;
4
+ const column_index_to_letter_js_1 = require("./column-index-to-letter.js");
5
+ const escape_xml_js_1 = require("./escape-xml.js");
6
+ function prepareRowToCells(row, rowNumber) {
7
+ return row.map((value, colIndex) => {
8
+ const colLetter = (0, column_index_to_letter_js_1.columnIndexToLetter)(colIndex);
9
+ const cellRef = `${colLetter}${rowNumber}`;
10
+ const cellValue = (0, escape_xml_js_1.escapeXml)(String(value ?? ""));
11
+ return `<c r="${cellRef}" t="inlineStr"><is><t>${cellValue}</t></is></c>`;
12
+ });
13
+ }
@@ -0,0 +1,40 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.processMergeCells = processMergeCells;
4
+ /**
5
+ * Processes the sheet XML by extracting the initial <mergeCells> block and
6
+ * extracting all merge cell references. The function returns an object with
7
+ * three properties:
8
+ * - `initialMergeCells`: The initial <mergeCells> block as a string array.
9
+ * - `mergeCellMatches`: An array of objects with `from` and `to` properties,
10
+ * representing the merge cell references.
11
+ * - `modifiedXml`: The modified sheet XML with the <mergeCells> block removed.
12
+ *
13
+ * @param sheetXml - The sheet XML string.
14
+ * @returns An object with the above three properties.
15
+ */
16
+ function processMergeCells(sheetXml) {
17
+ // Regular expression for finding <mergeCells> block
18
+ const mergeCellsBlockRegex = /<mergeCells[^>]*>[\s\S]*?<\/mergeCells>/;
19
+ // Find the first <mergeCells> block (if there are multiple, in xlsx usually there is only one)
20
+ const mergeCellsBlockMatch = sheetXml.match(mergeCellsBlockRegex);
21
+ const initialMergeCells = [];
22
+ const mergeCellMatches = [];
23
+ if (mergeCellsBlockMatch) {
24
+ const mergeCellsBlock = mergeCellsBlockMatch[0];
25
+ initialMergeCells.push(mergeCellsBlock);
26
+ // Extract <mergeCell ref="A1:B2"/> from this block
27
+ const mergeCellRegex = /<mergeCell ref="([A-Z]+\d+):([A-Z]+\d+)"\/>/g;
28
+ for (const match of mergeCellsBlock.matchAll(mergeCellRegex)) {
29
+ mergeCellMatches.push({ from: match[1], to: match[2] });
30
+ }
31
+ }
32
+ // Remove the <mergeCells> block from the XML
33
+ const modifiedXml = sheetXml.replace(mergeCellsBlockRegex, "");
34
+ return {
35
+ initialMergeCells,
36
+ mergeCellMatches,
37
+ modifiedXml,
38
+ };
39
+ }
40
+ ;
@@ -0,0 +1,51 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.processMergeFinalize = processMergeFinalize;
4
+ const update_dimension_js_1 = require("./update-dimension.js");
5
+ /**
6
+ * Finalizes the processing of the merged sheet by updating the merge cells and
7
+ * inserting them into the sheet XML. It also returns the modified sheet XML and
8
+ * shared strings.
9
+ *
10
+ * @param {object} data - An object containing the following properties:
11
+ * - `initialMergeCells`: The initial merge cells from the original sheet.
12
+ * - `lastIndex`: The last processed position in the sheet XML.
13
+ * - `mergeCellMatches`: An array of objects with `from` and `to` properties,
14
+ * describing the merge cells.
15
+ * - `resultRows`: An array of processed XML rows.
16
+ * - `rowShift`: The total row shift.
17
+ * - `sharedStrings`: An array of shared strings.
18
+ * - `sharedStringsHeader`: The XML declaration of the shared strings.
19
+ * - `sheetMergeCells`: An array of merge cell XML strings.
20
+ * - `sheetXml`: The original sheet XML string.
21
+ *
22
+ * @returns An object with two properties:
23
+ * - `shared`: The modified shared strings XML string.
24
+ * - `sheet`: The modified sheet XML string with updated merge cells.
25
+ */
26
+ function processMergeFinalize(data) {
27
+ const { initialMergeCells, lastIndex, mergeCellMatches, resultRows, rowShift, sharedStrings, sharedStringsHeader, sheetMergeCells, sheetXml, } = data;
28
+ for (const { from, to } of mergeCellMatches) {
29
+ const [, fromCol, fromRow] = from.match(/^([A-Z]+)(\d+)$/);
30
+ const [, toCol, toRow] = to.match(/^([A-Z]+)(\d+)$/);
31
+ const fromRowNum = Number(fromRow);
32
+ // These rows have already been processed, don't add duplicates
33
+ if (fromRowNum <= lastIndex)
34
+ continue;
35
+ const newFrom = `${fromCol}${fromRowNum + rowShift}`;
36
+ const newTo = `${toCol}${Number(toRow) + rowShift}`;
37
+ sheetMergeCells.push(`<mergeCell ref="${newFrom}:${newTo}"/>`);
38
+ }
39
+ resultRows.push(sheetXml.slice(lastIndex));
40
+ // Form XML for mergeCells if there are any
41
+ const mergeXml = sheetMergeCells.length
42
+ ? `<mergeCells count="${sheetMergeCells.length}">${sheetMergeCells.join("")}</mergeCells>`
43
+ : initialMergeCells;
44
+ // Insert mergeCells before the closing sheetData tag
45
+ const sheetWithMerge = resultRows.join("").replace(/<\/sheetData>/, `</sheetData>${mergeXml}`);
46
+ // Return modified sheet XML and shared strings
47
+ return {
48
+ shared: `${sharedStringsHeader}\n<sst xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" count="${sharedStrings.length}" uniqueCount="${sharedStrings.length}">${sharedStrings.join("")}</sst>`,
49
+ sheet: (0, update_dimension_js_1.updateDimension)(sheetWithMerge),
50
+ };
51
+ }