@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,160 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.processRows = processRows;
4
+ /**
5
+ * Processes a sheet XML by replacing table placeholders with real data and adjusting row numbers accordingly.
6
+ *
7
+ * @param data - An object containing the following properties:
8
+ * - `replacements`: An object where keys are table names and values are arrays of objects with table data.
9
+ * - `sharedIndexMap`: A Map of shared string indexes by their text content.
10
+ * - `mergeCellMatches`: An array of objects with `from` and `to` properties, describing the merge cells.
11
+ * - `sharedStrings`: An array of shared strings.
12
+ * - `sheetMergeCells`: An array of merge cell XML strings.
13
+ * - `sheetXml`: The sheet XML string.
14
+ *
15
+ * @returns An object with the following properties:
16
+ * - `lastIndex`: The last processed position in the sheet XML.
17
+ * - `resultRows`: An array of processed XML rows.
18
+ * - `rowShift`: The total row shift.
19
+ */
20
+ function processRows(data) {
21
+ const { mergeCellMatches, replacements, sharedIndexMap, sharedStrings, sheetMergeCells, sheetXml, } = data;
22
+ const TABLE_REGEX = /\$\{table:([a-zA-Z0-9_]+)\.([a-zA-Z0-9_]+)\}/g;
23
+ // Array for storing resulting XML rows
24
+ const resultRows = [];
25
+ // Previous position of processed part of XML
26
+ let lastIndex = 0;
27
+ // Shift for row numbers
28
+ let rowShift = 0;
29
+ // Regular expression for finding <row> elements
30
+ const rowRegex = /<row[^>]*?>[\s\S]*?<\/row>/g;
31
+ // Process each <row> element
32
+ for (const match of sheetXml.matchAll(rowRegex)) {
33
+ // Full XML row
34
+ const fullRow = match[0];
35
+ // Start position of the row in XML
36
+ const matchStart = match.index;
37
+ // End position of the row in XML
38
+ const matchEnd = matchStart + fullRow.length;
39
+ // Add the intermediate XML chunk (if any) between the previous and the current row
40
+ if (lastIndex !== matchStart) {
41
+ resultRows.push(sheetXml.slice(lastIndex, matchStart));
42
+ }
43
+ lastIndex = matchEnd;
44
+ // Get row number from r attribute
45
+ const originalRowNumber = parseInt(fullRow.match(/<row[^>]* r="(\d+)"/)?.[1] ?? "1", 10);
46
+ // Update row number based on rowShift
47
+ const shiftedRowNumber = originalRowNumber + rowShift;
48
+ // Find shared string indexes in cells of the current row
49
+ const sharedValueIndexes = [];
50
+ // Regular expression for finding a cell
51
+ const cellRegex = /<c[^>]*?r="([A-Z]+\d+)"[^>]*?>([\s\S]*?)<\/c>/g;
52
+ for (const cell of fullRow.matchAll(cellRegex)) {
53
+ const cellTag = cell[0];
54
+ // Check if the cell is a shared string
55
+ const isShared = /t="s"/.test(cellTag);
56
+ const valueMatch = cellTag.match(/<v>(\d+)<\/v>/);
57
+ if (isShared && valueMatch) {
58
+ sharedValueIndexes.push(parseInt(valueMatch[1], 10));
59
+ }
60
+ }
61
+ // Get the text content of shared strings by their indexes
62
+ const sharedTexts = sharedValueIndexes.map(i => sharedStrings[i]?.replace(/<\/?si>/g, "") ?? "");
63
+ // Find table placeholders in shared strings
64
+ const tablePlaceholders = sharedTexts.flatMap(e => [...e.matchAll(TABLE_REGEX)]);
65
+ // If there are no table placeholders, just shift the row
66
+ if (tablePlaceholders.length === 0) {
67
+ const updatedRow = fullRow
68
+ .replace(/(<row[^>]* r=")(\d+)(")/, `$1${shiftedRowNumber}$3`)
69
+ .replace(/<c r="([A-Z]+)(\d+)"/g, (_, col) => `<c r="${col}${shiftedRowNumber}"`);
70
+ resultRows.push(updatedRow);
71
+ // Update mergeCells for regular row with rowShift
72
+ const calculatedRowNumber = originalRowNumber + rowShift;
73
+ for (const { from, to } of mergeCellMatches) {
74
+ const [, fromCol, fromRow] = from.match(/^([A-Z]+)(\d+)$/);
75
+ const [, toCol] = to.match(/^([A-Z]+)(\d+)$/);
76
+ if (Number(fromRow) === calculatedRowNumber) {
77
+ const newFrom = `${fromCol}${shiftedRowNumber}`;
78
+ const newTo = `${toCol}${shiftedRowNumber}`;
79
+ sheetMergeCells.push(`<mergeCell ref="${newFrom}:${newTo}"/>`);
80
+ }
81
+ }
82
+ continue;
83
+ }
84
+ // Get the table name from the first placeholder
85
+ const firstMatch = tablePlaceholders[0];
86
+ const tableName = firstMatch?.[1];
87
+ if (!tableName)
88
+ throw new Error("Table name not found");
89
+ // Get data for replacement from replacements
90
+ const array = replacements[tableName];
91
+ if (!array)
92
+ continue;
93
+ if (!Array.isArray(array))
94
+ throw new Error("Table data is not an array");
95
+ const tableRowStart = shiftedRowNumber;
96
+ // Find mergeCells to duplicate (mergeCells that start with the current row)
97
+ const mergeCellsToDuplicate = mergeCellMatches.filter(({ from }) => {
98
+ const match = from.match(/^([A-Z]+)(\d+)$/);
99
+ if (!match)
100
+ return false;
101
+ // Row number of the merge cell start position is in the second group
102
+ const rowNumber = match[2];
103
+ return Number(rowNumber) === tableRowStart;
104
+ });
105
+ // Change the current row to multiple rows from the data array
106
+ for (let i = 0; i < array.length; i++) {
107
+ const rowData = array[i];
108
+ let newRow = fullRow;
109
+ // Replace placeholders in shared strings with real data
110
+ sharedValueIndexes.forEach((originalIdx, idx) => {
111
+ const originalText = sharedTexts[idx];
112
+ if (!originalText)
113
+ throw new Error("Shared value not found");
114
+ // Replace placeholders ${tableName.field} with real data from array data
115
+ const replacedText = originalText.replace(TABLE_REGEX, (_, tbl, field) => tbl === tableName ? String(rowData?.[field] ?? "") : "");
116
+ // Add new text to shared strings if it doesn't exist
117
+ let newIndex;
118
+ if (sharedIndexMap.has(replacedText)) {
119
+ newIndex = sharedIndexMap.get(replacedText);
120
+ }
121
+ else {
122
+ newIndex = sharedStrings.length;
123
+ sharedIndexMap.set(replacedText, newIndex);
124
+ sharedStrings.push(`<si>${replacedText}</si>`);
125
+ }
126
+ // Replace the shared string index in the cell
127
+ newRow = newRow.replace(`<v>${originalIdx}</v>`, `<v>${newIndex}</v>`);
128
+ });
129
+ // Update row number and cell references
130
+ const newRowNum = shiftedRowNumber + i;
131
+ newRow = newRow
132
+ .replace(/<row[^>]* r="\d+"/, rowTag => rowTag.replace(/r="\d+"/, `r="${newRowNum}"`))
133
+ .replace(/<c r="([A-Z]+)\d+"/g, (_, col) => `<c r="${col}${newRowNum}"`);
134
+ resultRows.push(newRow);
135
+ // Add duplicate mergeCells for new rows
136
+ for (const { from, to } of mergeCellsToDuplicate) {
137
+ const [, colFrom, rowFrom] = from.match(/^([A-Z]+)(\d+)$/);
138
+ const [, colTo, rowTo] = to.match(/^([A-Z]+)(\d+)$/);
139
+ const newFrom = `${colFrom}${Number(rowFrom) + i}`;
140
+ const newTo = `${colTo}${Number(rowTo) + i}`;
141
+ sheetMergeCells.push(`<mergeCell ref="${newFrom}:${newTo}"/>`);
142
+ }
143
+ }
144
+ // It increases the row shift by the number of added rows minus one replaced
145
+ rowShift += array.length - 1;
146
+ const delta = array.length - 1;
147
+ const calculatedRowNumber = originalRowNumber + rowShift - array.length + 1;
148
+ if (delta > 0) {
149
+ for (const merge of mergeCellMatches) {
150
+ const fromRow = parseInt(merge.from.match(/\d+$/)[0], 10);
151
+ if (fromRow > calculatedRowNumber) {
152
+ merge.from = merge.from.replace(/\d+$/, r => `${parseInt(r) + delta}`);
153
+ merge.to = merge.to.replace(/\d+$/, r => `${parseInt(r) + delta}`);
154
+ }
155
+ }
156
+ }
157
+ }
158
+ return { lastIndex, resultRows, rowShift };
159
+ }
160
+ ;
@@ -0,0 +1,45 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.processSharedStrings = processSharedStrings;
4
+ const extract_xml_declaration_js_1 = require("./extract-xml-declaration.js");
5
+ /**
6
+ * Processes the shared strings XML by extracting the XML declaration,
7
+ * extracting individual <si> elements, and storing them in an array.
8
+ *
9
+ * The function returns an object with four properties:
10
+ * - sharedIndexMap: A map of shared string content to their corresponding index
11
+ * - sharedStrings: An array of shared strings
12
+ * - sharedStringsHeader: The XML declaration of the shared strings
13
+ * - sheetMergeCells: An empty array, which is only used for type compatibility
14
+ * with the return type of processBuild.
15
+ *
16
+ * @param sharedStringsXml - The XML string of the shared strings
17
+ * @returns An object with the four properties above
18
+ */
19
+ function processSharedStrings(sharedStringsXml) {
20
+ // Final list of merged cells with all changes
21
+ const sheetMergeCells = [];
22
+ // Array for storing shared strings
23
+ const sharedStrings = [];
24
+ const sharedStringsHeader = (0, extract_xml_declaration_js_1.extractXmlDeclaration)(sharedStringsXml);
25
+ // Map for fast lookup of shared string index by content
26
+ const sharedIndexMap = new Map();
27
+ // Regular expression for finding <si> elements (shared string items)
28
+ const siRegex = /<si>([\s\S]*?)<\/si>/g;
29
+ // Parse sharedStringsXml and fill sharedStrings and sharedIndexMap
30
+ for (const match of sharedStringsXml.matchAll(siRegex)) {
31
+ const content = match[1];
32
+ if (!content)
33
+ continue;
34
+ const fullSi = `<si>${content}</si>`;
35
+ sharedIndexMap.set(content, sharedStrings.length);
36
+ sharedStrings.push(fullSi);
37
+ }
38
+ return {
39
+ sharedIndexMap,
40
+ sharedStrings,
41
+ sharedStringsHeader,
42
+ sheetMergeCells,
43
+ };
44
+ }
45
+ ;
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.toExcelColumnObject = toExcelColumnObject;
4
+ const column_index_to_letter_js_1 = require("./column-index-to-letter.js");
4
5
  /**
5
6
  * Converts an array of values into a Record<string, string> with Excel column names as keys.
6
7
  *
@@ -11,18 +12,9 @@ exports.toExcelColumnObject = toExcelColumnObject;
11
12
  * @returns The resulting Record<string, string>
12
13
  */
13
14
  function toExcelColumnObject(values) {
14
- const toExcelColumn = (index) => {
15
- let column = "";
16
- let i = index;
17
- while (i >= 0) {
18
- column = String.fromCharCode((i % 26) + 65) + column;
19
- i = Math.floor(i / 26) - 1;
20
- }
21
- return column;
22
- };
23
15
  const result = {};
24
16
  for (let i = 0; i < values.length; i++) {
25
- const key = toExcelColumn(i);
17
+ const key = (0, column_index_to_letter_js_1.columnIndexToLetter)(i);
26
18
  result[key] = String(values[i]);
27
19
  }
28
20
  return result;
@@ -1,22 +1,35 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.validateWorksheetXml = validateWorksheetXml;
4
+ /**
5
+ * Validates an Excel worksheet XML against the expected structure and rules.
6
+ *
7
+ * Checks the following:
8
+ * 1. XML starts with <?xml declaration
9
+ * 2. Root element is worksheet
10
+ * 3. Required elements are present
11
+ * 4. row numbers are in ascending order
12
+ * 5. No duplicate row numbers
13
+ * 6. No overlapping merge ranges
14
+ * 7. All cells are within the specified dimension
15
+ * 8. All mergeCell tags refer to existing cells
16
+ *
17
+ * @param xml The raw XML content of the worksheet
18
+ * @returns A ValidationResult object indicating if the XML is valid, and an error message if it's not
19
+ */
4
20
  function validateWorksheetXml(xml) {
5
21
  const createError = (message, details) => ({
6
- error: {
7
- details,
8
- message,
9
- },
22
+ error: { details, message },
10
23
  isValid: false,
11
24
  });
12
- // 1. Проверка базовой структуры XML
25
+ // 1. Check for XML declaration
13
26
  if (!xml.startsWith("<?xml")) {
14
- return createError("XML должен начинаться с декларации <?xml>");
27
+ return createError("XML must start with <?xml> declaration");
15
28
  }
16
29
  if (!xml.includes("<worksheet") || !xml.includes("</worksheet>")) {
17
- return createError("Не найден корневой элемент worksheet");
30
+ return createError("Root element worksheet not found");
18
31
  }
19
- // 2. Проверка наличия обязательных элементов
32
+ // 2. Check for required elements
20
33
  const requiredElements = [
21
34
  { name: "sheetViews", tag: "<sheetViews>" },
22
35
  { name: "sheetFormatPr", tag: "<sheetFormatPr" },
@@ -26,59 +39,59 @@ function validateWorksheetXml(xml) {
26
39
  ];
27
40
  for (const { name, tag } of requiredElements) {
28
41
  if (!xml.includes(tag)) {
29
- return createError(`Отсутствует обязательный элемент ${name}`);
42
+ return createError(`Missing required element ${name}`);
30
43
  }
31
44
  }
32
- // 3. Извлечение и проверка sheetData
45
+ // 3. Extract and validate sheetData
33
46
  const sheetDataStart = xml.indexOf("<sheetData>");
34
47
  const sheetDataEnd = xml.indexOf("</sheetData>");
35
48
  if (sheetDataStart === -1 || sheetDataEnd === -1) {
36
- return createError("Некорректная структура sheetData");
49
+ return createError("Invalid sheetData structure");
37
50
  }
38
51
  const sheetDataContent = xml.substring(sheetDataStart + 10, sheetDataEnd);
39
52
  const rows = sheetDataContent.split("</row>");
40
53
  if (rows.length < 2) {
41
- return createError("SheetData должен содержать хотя бы одну строку");
54
+ return createError("SheetData should contain at least one row");
42
55
  }
43
- // Собираем информацию о всех строках и ячейках
56
+ // Collect information about all rows and cells
44
57
  const allRows = [];
45
58
  const allCells = [];
46
59
  let prevRowNum = 0;
47
60
  for (const row of rows.slice(0, -1)) {
48
61
  if (!row.includes("<row ")) {
49
- return createError("Не найден тег row", `Фрагмент: ${row.substring(0, 50)}...`);
62
+ return createError("Row tag not found", `Fragment: ${row.substring(0, 50)}...`);
50
63
  }
51
64
  if (!row.includes("<c ")) {
52
- return createError("Строка не содержит ячеек", `Строка: ${row.substring(0, 50)}...`);
65
+ return createError("Row does not contain any cells", `Row: ${row.substring(0, 50)}...`);
53
66
  }
54
- // Извлекаем номер строки
67
+ // Extract row number
55
68
  const rowNumMatch = row.match(/<row\s+r="(\d+)"/);
56
69
  if (!rowNumMatch) {
57
- return createError("Не указан номер строки (атрибут r)", `Строка: ${row.substring(0, 50)}...`);
70
+ return createError("Row number (attribute r) not specified", `Row: ${row.substring(0, 50)}...`);
58
71
  }
59
72
  const rowNum = parseInt(rowNumMatch[1]);
60
- // Проверка уникальности строк
73
+ // Check for duplicate row numbers
61
74
  if (allRows.includes(rowNum)) {
62
- return createError("Найден дубликат номера строки", `Номер строки: ${rowNum}`);
75
+ return createError("Duplicate row number found", `Row number: ${rowNum}`);
63
76
  }
64
77
  allRows.push(rowNum);
65
- // Проверка порядка строк (должны идти по возрастанию)
78
+ // Check row number order (should be in ascending order)
66
79
  if (rowNum <= prevRowNum) {
67
- return createError("Нарушен порядок следования строк", `Текущая строка: ${rowNum}, предыдущая: ${prevRowNum}`);
80
+ return createError("Row order is broken", `Current row: ${rowNum}, previous: ${prevRowNum}`);
68
81
  }
69
82
  prevRowNum = rowNum;
70
- // Извлекаем все ячейки в строке
83
+ // Extract all cells in the row
71
84
  const cells = row.match(/<c\s+r="([A-Z]+)(\d+)"/g) || [];
72
85
  for (const cell of cells) {
73
86
  const match = cell.match(/<c\s+r="([A-Z]+)(\d+)"/);
74
87
  if (!match) {
75
- return createError("Некорректный формат ячейки", `Ячейка: ${cell}`);
88
+ return createError("Invalid cell format", `Cell: ${cell}`);
76
89
  }
77
90
  const col = match[1];
78
91
  const cellRowNum = parseInt(match[2]);
79
- // Проверяем соответствие номера строки
92
+ // Check row number match for each cell
80
93
  if (cellRowNum !== rowNum) {
81
- return createError("Несоответствие номера строки в ячейке", `Ожидалось: ${rowNum}, найдено: ${cellRowNum} в ячейке ${col}${cellRowNum}`);
94
+ return createError("Row number mismatch in cell", `Expected: ${rowNum}, found: ${cellRowNum} in cell ${col}${cellRowNum}`);
82
95
  }
83
96
  allCells.push({
84
97
  col,
@@ -86,32 +99,32 @@ function validateWorksheetXml(xml) {
86
99
  });
87
100
  }
88
101
  }
89
- // 4. Проверка mergeCells
102
+ // 4. Check mergeCells
90
103
  const mergeCellsStart = xml.indexOf("<mergeCells");
91
104
  const mergeCellsEnd = xml.indexOf("</mergeCells>");
92
105
  if (mergeCellsStart === -1 || mergeCellsEnd === -1) {
93
- return createError("Некорректная структура mergeCells");
106
+ return createError("Invalid mergeCells structure");
94
107
  }
95
108
  const mergeCellsContent = xml.substring(mergeCellsStart, mergeCellsEnd);
96
109
  const countMatch = mergeCellsContent.match(/count="(\d+)"/);
97
110
  if (!countMatch) {
98
- return createError("Не указано количество объединенных ячеек (атрибут count)");
111
+ return createError("Count attribute not specified for mergeCells");
99
112
  }
100
113
  const mergeCellTags = mergeCellsContent.match(/<mergeCell\s+ref="([A-Z]+\d+:[A-Z]+\d+)"\s*\/>/g);
101
114
  if (!mergeCellTags) {
102
- return createError("Не найдены объединенные ячейки");
115
+ return createError("No merged cells found");
103
116
  }
104
- // Проверка соответствия заявленного количества и фактического
117
+ // Check if the number of mergeCells matches the count attribute
105
118
  if (mergeCellTags.length !== parseInt(countMatch[1])) {
106
- return createError("Несоответствие количества объединенных ячеек", `Ожидалось: ${countMatch[1]}, найдено: ${mergeCellTags.length}`);
119
+ return createError("Mismatch in the number of merged cells", `Expected: ${countMatch[1]}, found: ${mergeCellTags.length}`);
107
120
  }
108
- // Проверка на дублирующиеся mergeCell
121
+ // Check for duplicates of mergeCell
109
122
  const mergeRefs = new Set();
110
123
  const duplicates = new Set();
111
124
  for (const mergeTag of mergeCellTags) {
112
125
  const refMatch = mergeTag.match(/ref="([A-Z]+\d+:[A-Z]+\d+)"/);
113
126
  if (!refMatch) {
114
- return createError("Некорректный формат объединения ячеек", `Тег: ${mergeTag}`);
127
+ return createError("Invalid merge cell format", `Tag: ${mergeTag}`);
115
128
  }
116
129
  const ref = refMatch[1];
117
130
  if (mergeRefs.has(ref)) {
@@ -122,9 +135,9 @@ function validateWorksheetXml(xml) {
122
135
  }
123
136
  }
124
137
  if (duplicates.size > 0) {
125
- return createError("Найдены дублирующиеся объединения ячеек", `Дубликаты: ${Array.from(duplicates).join(", ")}`);
138
+ return createError("Duplicates of merged cells found", `Duplicates: ${Array.from(duplicates).join(", ")}`);
126
139
  }
127
- // Проверка пересекающихся объединений
140
+ // Check for overlapping merge ranges
128
141
  const mergedRanges = Array.from(mergeRefs).map(ref => {
129
142
  const [start, end] = ref.split(":");
130
143
  return {
@@ -139,14 +152,14 @@ function validateWorksheetXml(xml) {
139
152
  const a = mergedRanges[i];
140
153
  const b = mergedRanges[j];
141
154
  if (rangesIntersect(a, b)) {
142
- return createError("Найдены пересекающиеся объединения ячеек", `Пересекаются: ${getRangeString(a)} и ${getRangeString(b)}`);
155
+ return createError("Found intersecting merged cells", `Intersecting: ${getRangeString(a)} and ${getRangeString(b)}`);
143
156
  }
144
157
  }
145
158
  }
146
- // 5. Проверка dimension и соответствия с реальными данными
159
+ // 5. Check dimension and match with real data
147
160
  const dimensionMatch = xml.match(/<dimension\s+ref="([A-Z]+\d+:[A-Z]+\d+)"\s*\/>/);
148
161
  if (!dimensionMatch) {
149
- return createError("Не указана область данных (dimension)");
162
+ return createError("Data range (dimension) is not specified");
150
163
  }
151
164
  const [startCell, endCell] = dimensionMatch[1].split(":");
152
165
  const startCol = startCell.match(/[A-Z]+/)?.[0];
@@ -154,25 +167,25 @@ function validateWorksheetXml(xml) {
154
167
  const endCol = endCell.match(/[A-Z]+/)?.[0];
155
168
  const endRow = parseInt(endCell.match(/\d+/)?.[0] || "0");
156
169
  if (!startCol || !endCol || isNaN(startRow) || isNaN(endRow)) {
157
- return createError("Некорректный формат dimension", `Dimension: ${dimensionMatch[1]}`);
170
+ return createError("Invalid dimension format", `Dimension: ${dimensionMatch[1]}`);
158
171
  }
159
172
  const startColNum = colToNumber(startCol);
160
173
  const endColNum = colToNumber(endCol);
161
- // Проверяем все ячейки на вхождение в dimension
174
+ // Check if all cells are within the dimension
162
175
  for (const cell of allCells) {
163
176
  const colNum = colToNumber(cell.col);
164
177
  if (cell.row < startRow || cell.row > endRow) {
165
- return createError("Ячейка находится вне указанной области (по строке)", `Ячейка: ${cell.col}${cell.row}, dimension: ${dimensionMatch[1]}`);
178
+ return createError("Cell is outside the specified area (by row)", `Cell: ${cell.col}${cell.row}, dimension: ${dimensionMatch[1]}`);
166
179
  }
167
180
  if (colNum < startColNum || colNum > endColNum) {
168
- return createError("Ячейка находится вне указанной области (по столбцу)", `Ячейка: ${cell.col}${cell.row}, dimension: ${dimensionMatch[1]}`);
181
+ return createError("Cell is outside the specified area (by column)", `Cell: ${cell.col}${cell.row}, dimension: ${dimensionMatch[1]}`);
169
182
  }
170
183
  }
171
- // 6. Дополнительная проверка: все mergeCell ссылаются на существующие ячейки
184
+ // 6. Additional check: all mergeCell tags refer to existing cells
172
185
  for (const mergeTag of mergeCellTags) {
173
186
  const refMatch = mergeTag.match(/ref="([A-Z]+\d+:[A-Z]+\d+)"/);
174
187
  if (!refMatch) {
175
- return createError("Некорректный формат объединения ячеек", `Тег: ${mergeTag}`);
188
+ return createError("Invalid merge cell format", `Tag: ${mergeTag}`);
176
189
  }
177
190
  const [cell1, cell2] = refMatch[1].split(":");
178
191
  const cell1Col = cell1.match(/[A-Z]+/)?.[0];
@@ -180,33 +193,34 @@ function validateWorksheetXml(xml) {
180
193
  const cell2Col = cell2.match(/[A-Z]+/)?.[0];
181
194
  const cell2Row = parseInt(cell2.match(/\d+/)?.[0] || "0");
182
195
  if (!cell1Col || !cell2Col || isNaN(cell1Row) || isNaN(cell2Row)) {
183
- return createError("Некорректные координаты объединения ячеек", `Объединение: ${refMatch[1]}`);
196
+ return createError("Invalid merged cell coordinates", `Merged cells: ${refMatch[1]}`);
184
197
  }
185
- // Проверяем что объединяемые ячейки существуют
198
+ // Check if the merged cells exist
186
199
  const cell1Exists = allCells.some(c => c.row === cell1Row && c.col === cell1Col);
187
200
  const cell2Exists = allCells.some(c => c.row === cell2Row && c.col === cell2Col);
188
201
  if (!cell1Exists || !cell2Exists) {
189
- return createError("Объединение ссылается на несуществующие ячейки", `Объединение: ${refMatch[1]}, отсутствует: ${!cell1Exists ? `${cell1Col}${cell1Row}` : `${cell2Col}${cell2Row}`}`);
202
+ return createError("Merged cell reference points to non-existent cells", `Merged cells: ${refMatch[1]}, missing: ${!cell1Exists ? `${cell1Col}${cell1Row}` : `${cell2Col}${cell2Row}`}`);
190
203
  }
191
204
  }
192
205
  return { isValid: true };
193
206
  }
194
- // Вспомогательные функции для проверки пересечений
207
+ // A function to check if two ranges intersect
195
208
  function rangesIntersect(a, b) {
196
209
  const aStartColNum = colToNumber(a.startCol);
197
210
  const aEndColNum = colToNumber(a.endCol);
198
211
  const bStartColNum = colToNumber(b.startCol);
199
212
  const bEndColNum = colToNumber(b.endCol);
200
- // Проверяем пересечение по строкам
213
+ // Check if the rows intersect
201
214
  const rowsIntersect = !(a.endRow < b.startRow || a.startRow > b.endRow);
202
- // Проверяем пересечение по колонкам
215
+ // Check if the columns intersect
203
216
  const colsIntersect = !(aEndColNum < bStartColNum || aStartColNum > bEndColNum);
204
217
  return rowsIntersect && colsIntersect;
205
218
  }
219
+ // Function to get the range string1
206
220
  function getRangeString(range) {
207
221
  return `${range.startCol}${range.startRow}:${range.endCol}${range.endRow}`;
208
222
  }
209
- // Функция для преобразования букв колонки в число
223
+ // Function to convert column letters to numbers
210
224
  function colToNumber(col) {
211
225
  let num = 0;
212
226
  for (let i = 0; i < col.length; i++) {
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.writeRowsToStream = writeRowsToStream;
4
- const column_index_to_letter_js_1 = require("./column-index-to-letter.js");
4
+ const prepare_row_to_cells_js_1 = require("./prepare-row-to-cells.js");
5
5
  /**
6
6
  * Writes an async iterable of rows to an Excel XML file.
7
7
  *
@@ -27,15 +27,20 @@ async function writeRowsToStream(output, rows, startRowNumber) {
27
27
  let rowNumber = startRowNumber;
28
28
  for await (const row of rows) {
29
29
  // Transform the row into XML
30
- const cells = row.map((value, colIndex) => {
31
- const colLetter = (0, column_index_to_letter_js_1.columnIndexToLetter)(colIndex);
32
- const cellRef = `${colLetter}${rowNumber}`;
33
- const cellValue = String(value ?? "");
34
- return `<c r="${cellRef}" t="inlineStr"><is><t>${cellValue}</t></is></c>`;
35
- });
36
- // Write the row to the file
37
- output.write(`<row r="${rowNumber}">${cells.join("")}</row>`);
38
- rowNumber++;
30
+ if (Array.isArray(row[0])) {
31
+ for (const subRow of row) {
32
+ const cells = (0, prepare_row_to_cells_js_1.prepareRowToCells)(subRow, rowNumber);
33
+ // Write the row to the file
34
+ output.write(`<row r="${rowNumber}">${cells.join("")}</row>`);
35
+ rowNumber++;
36
+ }
37
+ }
38
+ else {
39
+ const cells = (0, prepare_row_to_cells_js_1.prepareRowToCells)(row, rowNumber);
40
+ // Write the row to the file
41
+ output.write(`<row r="${rowNumber}">${cells.join("")}</row>`);
42
+ rowNumber++;
43
+ }
39
44
  }
40
45
  return { rowNumber };
41
46
  }
@@ -1 +1,2 @@
1
1
  export * from "./template-fs.js";
2
+ export * from "./template-memory.js";
@@ -0,0 +1,13 @@
1
+ export class MemoryWriteStream {
2
+ chunks = [];
3
+ write(chunk) {
4
+ this.chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, "utf-8"));
5
+ return true;
6
+ }
7
+ end() {
8
+ // no-op
9
+ }
10
+ toBuffer() {
11
+ return Buffer.concat(this.chunks);
12
+ }
13
+ }