UNPKG

@microsoft/connected-workbooks

Version:

Microsoft backed, Excel advanced xlsx workbook generation JavaScript library

241 lines (240 loc) 14.6 kB
"use strict"; // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (g && (g = 0, op[0] && (_ = 0)), _) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); var constants_1 = require("./constants"); var documentUtils_1 = __importDefault(require("./documentUtils")); var uuid_1 = require("uuid"); var xmldom_qsa_1 = require("xmldom-qsa"); /** * Update initial data for a table, its sheet, query table, and defined name if provided. * @param zip - The JSZip instance containing workbook parts. * @param cellRangeRef - Cell range reference (e.g. "A1:C5"). * @param sheetPath - Path to the sheet XML within the zip. * @param tablePath - Path to the table XML within the zip. * @param tableName - Name of the table. * @param tableData - Optional TableData containing headers and rows. * @param updateQueryTable - Whether to update the associated queryTable part. */ var updateTableInitialDataIfNeeded = function (zip, cellRangeRef, sheetPath, tablePath, sheetName, tableData, updateQueryTable) { return __awaiter(void 0, void 0, void 0, function () { var sheetsXmlString, newSheet, queryTableXmlString, newQueryTable, workbookXmlString, newWorkbook, tableXmlString, newTable; var _a, _b, _c, _d; return __generator(this, function (_e) { switch (_e.label) { case 0: if (!tableData) { return [2 /*return*/]; } return [4 /*yield*/, ((_a = zip.file(sheetPath)) === null || _a === void 0 ? void 0 : _a.async(constants_1.textResultType))]; case 1: sheetsXmlString = _e.sent(); if (sheetsXmlString === undefined) { throw new Error(constants_1.Errors.sheetsNotFound); } newSheet = updateSheetsInitialData(sheetsXmlString, tableData, cellRangeRef); zip.file(sheetPath, newSheet); if (!updateQueryTable) return [3 /*break*/, 5]; return [4 /*yield*/, ((_b = zip.file(constants_1.queryTableXmlPath)) === null || _b === void 0 ? void 0 : _b.async(constants_1.textResultType))]; case 2: queryTableXmlString = _e.sent(); if (queryTableXmlString === undefined) { throw new Error(constants_1.Errors.queryTableNotFound); } return [4 /*yield*/, updateQueryTablesInitialData(queryTableXmlString, tableData)]; case 3: newQueryTable = _e.sent(); zip.file(constants_1.queryTableXmlPath, newQueryTable); return [4 /*yield*/, ((_c = zip.file(constants_1.workbookXmlPath)) === null || _c === void 0 ? void 0 : _c.async(constants_1.textResultType))]; case 4: workbookXmlString = _e.sent(); if (workbookXmlString === undefined) { throw new Error(constants_1.Errors.workbookNotFound); } newWorkbook = updateWorkbookInitialData(workbookXmlString, sheetName + GenerateReferenceFromString(cellRangeRef)); zip.file(constants_1.workbookXmlPath, newWorkbook); _e.label = 5; case 5: return [4 /*yield*/, ((_d = zip.file(tablePath)) === null || _d === void 0 ? void 0 : _d.async(constants_1.textResultType))]; case 6: tableXmlString = _e.sent(); if (tableXmlString === undefined) { throw new Error(constants_1.Errors.tableNotFound); } newTable = updateTablesInitialData(tableXmlString, tableData, cellRangeRef, updateQueryTable); zip.file(tablePath, newTable); return [2 /*return*/]; } }); }); }; /** * Generate updated table XML string with new columns, reference, and filter range. * @param tableXmlString - Original table XML. * @param tableData - TableData containing column names. * @param cellRangeRef - Cell range reference. * @param updateQueryTable - Whether to include queryTable attributes. * @returns Serialized XML string of the updated table. */ var updateTablesInitialData = function (tableXmlString, tableData, cellRangeRef, updateQueryTable) { if (updateQueryTable === void 0) { updateQueryTable = false; } var parser = new xmldom_qsa_1.DOMParser(); var serializer = new xmldom_qsa_1.XMLSerializer(); var tableDoc = parser.parseFromString(tableXmlString, constants_1.xmlTextResultType); var tableColumns = tableDoc.getElementsByTagName(constants_1.element.tableColumns)[0]; tableColumns.textContent = ""; tableData.columnNames.forEach(function (column, columnIndex) { var tableColumn = tableDoc.createElementNS(tableDoc.documentElement.namespaceURI, constants_1.element.tableColumn); tableColumn.setAttribute(constants_1.elementAttributes.id, (columnIndex + 1).toString()); tableColumn.setAttribute(constants_1.elementAttributes.name, column); tableColumns.appendChild(tableColumn); tableColumn.setAttribute(constants_1.elementAttributes.xr3uid, "{" + (0, uuid_1.v4)().toUpperCase() + "}"); if (updateQueryTable) { tableColumn.setAttribute(constants_1.elementAttributes.uniqueName, (columnIndex + 1).toString()); tableColumn.setAttribute(constants_1.elementAttributes.queryTableFieldId, (columnIndex + 1).toString()); } }); tableColumns.setAttribute(constants_1.elementAttributes.count, tableData.columnNames.length.toString()); tableDoc .getElementsByTagName(constants_1.element.table)[0] .setAttribute(constants_1.elementAttributes.reference, cellRangeRef); tableDoc .getElementsByTagName(constants_1.element.autoFilter)[0] .setAttribute(constants_1.elementAttributes.reference, cellRangeRef); return serializer.serializeToString(tableDoc); }; /** * Update the definedName element in workbook XML to a custom name. * @param workbookXmlString - Original workbook XML string. * @param customDefinedName - New defined name text content (e.g. "!$A$1:$C$5"). * @returns Serialized XML string of the updated workbook. */ var updateWorkbookInitialData = function (workbookXmlString, customDefinedName) { var newParser = new xmldom_qsa_1.DOMParser(); var newSerializer = new xmldom_qsa_1.XMLSerializer(); var workbookDoc = newParser.parseFromString(workbookXmlString, constants_1.xmlTextResultType); var definedName = workbookDoc.getElementsByTagName(constants_1.element.definedName)[0]; definedName.textContent = customDefinedName; return newSerializer.serializeToString(workbookDoc); }; var updateQueryTablesInitialData = function (queryTableXmlString, tableData) { var parser = new xmldom_qsa_1.DOMParser(); var serializer = new xmldom_qsa_1.XMLSerializer(); var queryTableDoc = parser.parseFromString(queryTableXmlString, constants_1.xmlTextResultType); var queryTableFields = queryTableDoc.getElementsByTagName(constants_1.element.queryTableFields)[0]; queryTableFields.textContent = ""; tableData.columnNames.forEach(function (column, columnIndex) { var queryTableField = queryTableDoc.createElementNS(queryTableDoc.documentElement.namespaceURI, constants_1.element.queryTableField); queryTableField.setAttribute(constants_1.elementAttributes.id, (columnIndex + 1).toString()); queryTableField.setAttribute(constants_1.elementAttributes.name, column); queryTableField.setAttribute(constants_1.elementAttributes.tableColumnId, (columnIndex + 1).toString()); queryTableFields.appendChild(queryTableField); }); queryTableFields.setAttribute(constants_1.elementAttributes.count, tableData.columnNames.length.toString()); queryTableDoc.getElementsByTagName(constants_1.element.queryTableRefresh)[0].setAttribute(constants_1.elementAttributes.nextId, (tableData.columnNames.length + 1).toString()); return serializer.serializeToString(queryTableDoc); }; /** * Update sheet XML with header row and data rows based on TableData. * @param sheetsXmlString - Original sheet XML string. * @param tableData - TableData containing headers and rows. * @param cellRangeRef - Cell range reference. * @returns Serialized XML string of the updated sheet. */ var updateSheetsInitialData = function (sheetsXmlString, tableData, cellRangeRef) { var _a = documentUtils_1.default.GetStartPosition(cellRangeRef), row = _a.row, column = _a.column; var parser = new xmldom_qsa_1.DOMParser(); var serializer = new xmldom_qsa_1.XMLSerializer(); var sheetsDoc = parser.parseFromString(sheetsXmlString, constants_1.xmlTextResultType); var sheetData = sheetsDoc.getElementsByTagName(constants_1.element.sheetData)[0]; sheetData.textContent = ""; var columnRow = sheetsDoc.createElementNS(sheetsDoc.documentElement.namespaceURI, constants_1.element.row); columnRow.setAttribute(constants_1.elementAttributes.row, row.toString()); columnRow.setAttribute(constants_1.elementAttributes.spans, column + ":" + (column + tableData.columnNames.length - 1)); columnRow.setAttribute(constants_1.elementAttributes.x14acDyDescent, "0.3"); tableData.columnNames.forEach(function (col, colIndex) { validateCellContentLength(col); columnRow.appendChild(documentUtils_1.default.createCell(sheetsDoc, colIndex + column - 1, row - 1, col)); }); sheetData.appendChild(columnRow); row++; tableData.rows.forEach(function (_row) { var newRow = sheetsDoc.createElementNS(sheetsDoc.documentElement.namespaceURI, constants_1.element.row); newRow.setAttribute(constants_1.elementAttributes.row, row.toString()); newRow.setAttribute(constants_1.elementAttributes.spans, column + ":" + (column + tableData.columnNames.length - 1)); newRow.setAttribute(constants_1.elementAttributes.x14acDyDescent, "0.3"); _row.forEach(function (cellContent, colIndex) { validateCellContentLength(cellContent); newRow.appendChild(documentUtils_1.default.createCell(sheetsDoc, colIndex + column - 1, row - 1, cellContent)); }); sheetData.appendChild(newRow); row++; }); sheetsDoc.getElementsByTagName(constants_1.element.dimension)[0].setAttribute(constants_1.elementAttributes.reference, cellRangeRef); sheetsDoc.getElementsByTagName(constants_1.element.selection)[0].setAttribute(constants_1.elementAttributes.sqref, cellRangeRef); return serializer.serializeToString(sheetsDoc); }; var validateCellContentLength = function (cellContent) { if (cellContent.length > constants_1.maxCellCharacters) { throw new Error(constants_1.Errors.invalidCellValueErr); } }; /** * Add Excel-style dollar signs and a '!' prefix to a cell range. * Converts "A1:B2" into "!$A$1:$B$2". * @param cellRangeRef - Range reference string without dollar signs. * @returns Range with dollar signs and prefix. */ var GenerateReferenceFromString = function (cellRangeRef) { return "!" + cellRangeRef.split(":").map(function (part) { var match = part.match(/^([A-Za-z]+)(\d+)$/); if (match) { var col = match[1], row = match[2]; return "$".concat(col.toUpperCase(), "$").concat(row); } }).join(":"); }; exports.default = { updateTableInitialDataIfNeeded: updateTableInitialDataIfNeeded, updateSheetsInitialData: updateSheetsInitialData, updateWorkbookInitialData: updateWorkbookInitialData, updateTablesInitialData: updateTablesInitialData, updateQueryTablesInitialData: updateQueryTablesInitialData, GenerateReferenceFromString: GenerateReferenceFromString, };