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