UNPKG

@zlooun/exceljs

Version:

Fixes the problem with writing a file using streams and not using RAM based on 'exeljs'

854 lines (802 loc) 44.7 kB
"use strict"; function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return exports; }; var exports = {}, Op = Object.prototype, hasOwn = Op.hasOwnProperty, defineProperty = Object.defineProperty || function (obj, key, desc) { obj[key] = desc.value; }, $Symbol = "function" == typeof Symbol ? Symbol : {}, iteratorSymbol = $Symbol.iterator || "@@iterator", asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator", toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; function define(obj, key, value) { return Object.defineProperty(obj, key, { value: value, enumerable: !0, configurable: !0, writable: !0 }), obj[key]; } try { define({}, ""); } catch (err) { define = function define(obj, key, value) { return obj[key] = value; }; } function wrap(innerFn, outerFn, self, tryLocsList) { var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator, generator = Object.create(protoGenerator.prototype), context = new Context(tryLocsList || []); return defineProperty(generator, "_invoke", { value: makeInvokeMethod(innerFn, self, context) }), generator; } function tryCatch(fn, obj, arg) { try { return { type: "normal", arg: fn.call(obj, arg) }; } catch (err) { return { type: "throw", arg: err }; } } exports.wrap = wrap; var ContinueSentinel = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var IteratorPrototype = {}; define(IteratorPrototype, iteratorSymbol, function () { return this; }); var getProto = Object.getPrototypeOf, NativeIteratorPrototype = getProto && getProto(getProto(values([]))); NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype); var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); function defineIteratorMethods(prototype) { ["next", "throw", "return"].forEach(function (method) { define(prototype, method, function (arg) { return this._invoke(method, arg); }); }); } function AsyncIterator(generator, PromiseImpl) { function invoke(method, arg, resolve, reject) { var record = tryCatch(generator[method], generator, arg); if ("throw" !== record.type) { var result = record.arg, value = result.value; return value && "object" == _typeof(value) && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) { invoke("next", value, resolve, reject); }, function (err) { invoke("throw", err, resolve, reject); }) : PromiseImpl.resolve(value).then(function (unwrapped) { result.value = unwrapped, resolve(result); }, function (error) { return invoke("throw", error, resolve, reject); }); } reject(record.arg); } var previousPromise; defineProperty(this, "_invoke", { value: function value(method, arg) { function callInvokeWithMethodAndArg() { return new PromiseImpl(function (resolve, reject) { invoke(method, arg, resolve, reject); }); } return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(innerFn, self, context) { var state = "suspendedStart"; return function (method, arg) { if ("executing" === state) throw new Error("Generator is already running"); if ("completed" === state) { if ("throw" === method) throw arg; return doneResult(); } for (context.method = method, context.arg = arg;;) { var delegate = context.delegate; if (delegate) { var delegateResult = maybeInvokeDelegate(delegate, context); if (delegateResult) { if (delegateResult === ContinueSentinel) continue; return delegateResult; } } if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) { if ("suspendedStart" === state) throw state = "completed", context.arg; context.dispatchException(context.arg); } else "return" === context.method && context.abrupt("return", context.arg); state = "executing"; var record = tryCatch(innerFn, self, context); if ("normal" === record.type) { if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue; return { value: record.arg, done: context.done }; } "throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg); } }; } function maybeInvokeDelegate(delegate, context) { var methodName = context.method, method = delegate.iterator[methodName]; if (undefined === method) return context.delegate = null, "throw" === methodName && delegate.iterator.return && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method) || "return" !== methodName && (context.method = "throw", context.arg = new TypeError("The iterator does not provide a '" + methodName + "' method")), ContinueSentinel; var record = tryCatch(method, delegate.iterator, context.arg); if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel; var info = record.arg; return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel); } function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; 1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry); } function resetTryEntry(entry) { var record = entry.completion || {}; record.type = "normal", delete record.arg, entry.completion = record; } function Context(tryLocsList) { this.tryEntries = [{ tryLoc: "root" }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0); } function values(iterable) { if (iterable) { var iteratorMethod = iterable[iteratorSymbol]; if (iteratorMethod) return iteratorMethod.call(iterable); if ("function" == typeof iterable.next) return iterable; if (!isNaN(iterable.length)) { var i = -1, next = function next() { for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next; return next.value = undefined, next.done = !0, next; }; return next.next = next; } } return { next: doneResult }; } function doneResult() { return { value: undefined, done: !0 }; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, defineProperty(Gp, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), defineProperty(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) { var ctor = "function" == typeof genFun && genFun.constructor; return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name)); }, exports.mark = function (genFun) { return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun; }, exports.awrap = function (arg) { return { __await: arg }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () { return this; }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) { void 0 === PromiseImpl && (PromiseImpl = Promise); var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl); return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) { return result.done ? result.value : iter.next(); }); }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () { return this; }), define(Gp, "toString", function () { return "[object Generator]"; }), exports.keys = function (val) { var object = Object(val), keys = []; for (var key in object) keys.push(key); return keys.reverse(), function next() { for (; keys.length;) { var key = keys.pop(); if (key in object) return next.value = key, next.done = !1, next; } return next.done = !0, next; }; }, exports.values = values, Context.prototype = { constructor: Context, reset: function reset(skipTempReset) { if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) "t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined); }, stop: function stop() { this.done = !0; var rootRecord = this.tryEntries[0].completion; if ("throw" === rootRecord.type) throw rootRecord.arg; return this.rval; }, dispatchException: function dispatchException(exception) { if (this.done) throw exception; var context = this; function handle(loc, caught) { return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught; } for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i], record = entry.completion; if ("root" === entry.tryLoc) return handle("end"); if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn.call(entry, "catchLoc"), hasFinally = hasOwn.call(entry, "finallyLoc"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } else if (hasCatch) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); } else { if (!hasFinally) throw new Error("try statement without catch or finally"); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } } } }, abrupt: function abrupt(type, arg) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) { var finallyEntry = entry; break; } } finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null); var record = finallyEntry ? finallyEntry.completion : {}; return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record); }, complete: function complete(record, afterLoc) { if ("throw" === record.type) throw record.arg; return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel; }, finish: function finish(finallyLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel; } }, catch: function _catch(tryLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc === tryLoc) { var record = entry.completion; if ("throw" === record.type) { var thrown = record.arg; resetTryEntry(entry); } return thrown; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(iterable, resultName, nextLoc) { return this.delegate = { iterator: values(iterable), resultName: resultName, nextLoc: nextLoc }, "next" === this.method && (this.arg = undefined), ContinueSentinel; } }, exports; } function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); } function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } var _ = require('../../utils/under-dash'); var RelType = require('../../xlsx/rel-type'); var colCache = require('../../utils/col-cache'); var Encryptor = require('../../utils/encryptor'); var Dimensions = require('../../doc/range'); var StringBuf = require('../../utils/string-buf'); var Row = require('../../doc/row'); var Column = require('../../doc/column'); var SheetRelsWriter = require('./sheet-rels-writer'); var SheetCommentsWriter = require('./sheet-comments-writer'); var DataValidations = require('../../doc/data-validations'); var xmlBuffer = new StringBuf(); // ============================================================================================ // Xforms var ListXform = require('../../xlsx/xform/list-xform'); var DataValidationsXform = require('../../xlsx/xform/sheet/data-validations-xform'); var SheetPropertiesXform = require('../../xlsx/xform/sheet/sheet-properties-xform'); var SheetFormatPropertiesXform = require('../../xlsx/xform/sheet/sheet-format-properties-xform'); var ColXform = require('../../xlsx/xform/sheet/col-xform'); var RowXform = require('../../xlsx/xform/sheet/row-xform'); var HyperlinkXform = require('../../xlsx/xform/sheet/hyperlink-xform'); var SheetViewXform = require('../../xlsx/xform/sheet/sheet-view-xform'); var SheetProtectionXform = require('../../xlsx/xform/sheet/sheet-protection-xform'); var PageMarginsXform = require('../../xlsx/xform/sheet/page-margins-xform'); var PageSetupXform = require('../../xlsx/xform/sheet/page-setup-xform'); var AutoFilterXform = require('../../xlsx/xform/sheet/auto-filter-xform'); var PictureXform = require('../../xlsx/xform/sheet/picture-xform'); var ConditionalFormattingsXform = require('../../xlsx/xform/sheet/cf/conditional-formattings-xform'); var HeaderFooterXform = require('../../xlsx/xform/sheet/header-footer-xform'); var RowBreaksXform = require('../../xlsx/xform/sheet/row-breaks-xform'); // since prepare and render are functional, we can use singletons var xform = { dataValidations: new DataValidationsXform(), sheetProperties: new SheetPropertiesXform(), sheetFormatProperties: new SheetFormatPropertiesXform(), columns: new ListXform({ tag: 'cols', length: false, childXform: new ColXform() }), row: new RowXform(), hyperlinks: new ListXform({ tag: 'hyperlinks', length: false, childXform: new HyperlinkXform() }), sheetViews: new ListXform({ tag: 'sheetViews', length: false, childXform: new SheetViewXform() }), sheetProtection: new SheetProtectionXform(), pageMargins: new PageMarginsXform(), pageSeteup: new PageSetupXform(), autoFilter: new AutoFilterXform(), picture: new PictureXform(), conditionalFormattings: new ConditionalFormattingsXform(), headerFooter: new HeaderFooterXform(), rowBreaks: new RowBreaksXform() }; // ============================================================================================ var WorksheetWriter = /*#__PURE__*/function () { function WorksheetWriter(options) { _classCallCheck(this, WorksheetWriter); // in a workbook, each sheet will have a number this.id = options.id; // and a name this.name = options.name || "Sheet".concat(this.id); // add a state this.state = options.state || 'visible'; // rows are stored here while they need to be worked on. // when they are committed, they will be deleted. this._rows = []; // column definitions this._columns = null; // column keys (addRow convenience): key ==> this._columns index this._keys = {}; // keep a record of all row and column pageBreaks this._merges = []; this._merges.add = function () {}; // ignore cell instruction // keep record of all hyperlinks this._sheetRelsWriter = new SheetRelsWriter(options); this._sheetCommentsWriter = new SheetCommentsWriter(this, this._sheetRelsWriter, options); // keep a record of dimensions this._dimensions = new Dimensions(); // first uncommitted row this._rowZero = 1; // committed flag this.committed = false; // for data validations this.dataValidations = new DataValidations(); // for sharing formulae this._formulae = {}; this._siFormulae = 0; // keep a record of conditionalFormattings this.conditionalFormatting = []; // keep a record of all row and column pageBreaks this.rowBreaks = []; // for default row height, outline levels, etc this.properties = Object.assign({}, { defaultRowHeight: 15, dyDescent: 55, outlineLevelCol: 0, outlineLevelRow: 0 }, options.properties); this.headerFooter = Object.assign({}, { differentFirst: false, differentOddEven: false, oddHeader: null, oddFooter: null, evenHeader: null, evenFooter: null, firstHeader: null, firstFooter: null }, options.headerFooter); // for all things printing this.pageSetup = Object.assign({}, { margins: { left: 0.7, right: 0.7, top: 0.75, bottom: 0.75, header: 0.3, footer: 0.3 }, orientation: 'portrait', horizontalDpi: 4294967295, verticalDpi: 4294967295, fitToPage: !!(options.pageSetup && (options.pageSetup.fitToWidth || options.pageSetup.fitToHeight) && !options.pageSetup.scale), pageOrder: 'downThenOver', blackAndWhite: false, draft: false, cellComments: 'None', errors: 'displayed', scale: 100, fitToWidth: 1, fitToHeight: 1, paperSize: undefined, showRowColHeaders: false, showGridLines: false, horizontalCentered: false, verticalCentered: false, rowBreaks: null, colBreaks: null }, options.pageSetup); // using shared strings creates a smaller xlsx file but may use more memory this.useSharedStrings = options.useSharedStrings || false; this._workbook = options.workbook; this.hasComments = false; // views this._views = options.views || []; // auto filter this.autoFilter = options.autoFilter || null; this._media = []; // worksheet protection this.sheetProtection = null; // start writing to stream now this._writeOpenWorksheet(); this.startedData = false; } _createClass(WorksheetWriter, [{ key: "workbook", get: function get() { return this._workbook; } }, { key: "stream", get: function get() { if (!this._stream) { // eslint-disable-next-line no-underscore-dangle this._stream = this._workbook._openStream("/xl/worksheets/sheet".concat(this.id, ".xml")); // pause stream to prevent 'data' events this._stream.pause(); } return this._stream; } // destroy - not a valid operation for a streaming writer // even though some streamers might be able to, it's a bad idea. }, { key: "destroy", value: function destroy() { throw new Error('Invalid Operation: destroy'); } }, { key: "commit", value: function () { var _commit = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() { var _iterator, _step, cRow; return _regeneratorRuntime().wrap(function _callee$(_context) { while (1) switch (_context.prev = _context.next) { case 0: if (!this.committed) { _context.next = 2; break; } return _context.abrupt("return"); case 2: // commit all rows _iterator = _createForOfIteratorHelper(this._rows); _context.prev = 3; _iterator.s(); case 5: if ((_step = _iterator.n()).done) { _context.next = 12; break; } cRow = _step.value; if (!cRow) { _context.next = 10; break; } _context.next = 10; return this._writeRow(cRow); case 10: _context.next = 5; break; case 12: _context.next = 17; break; case 14: _context.prev = 14; _context.t0 = _context["catch"](3); _iterator.e(_context.t0); case 17: _context.prev = 17; _iterator.f(); return _context.finish(17); case 20: // we _cannot_ accept new rows from now on this._rows = null; if (!this.startedData) { this._writeOpenSheetData(); } this._writeCloseSheetData(); this._writeAutoFilter(); this._writeMergeCells(); // for some reason, Excel can't handle dimensions at the bottom of the file // this._writeDimensions(); this._writeHyperlinks(); this._writeConditionalFormatting(); this._writeDataValidations(); this._writeSheetProtection(); this._writePageMargins(); this._writePageSetup(); this._writeBackground(); this._writeHeaderFooter(); this._writeRowBreaks(); // Legacy Data tag for comments this._writeLegacyData(); this._writeCloseWorksheet(); // signal end of stream to workbook this._sheetCommentsWriter.commit(); // also commit the hyperlinks if any this._sheetRelsWriter.commit(); _context.next = 40; return this.stream.end(); case 40: this.committed = true; case 41: case "end": return _context.stop(); } }, _callee, this, [[3, 14, 17, 20]]); })); function commit() { return _commit.apply(this, arguments); } return commit; }() // return the current dimensions of the writer }, { key: "dimensions", get: function get() { return this._dimensions; } }, { key: "views", get: function get() { return this._views; } // ========================================================================= // Columns // get the current columns array. }, { key: "columns", get: function get() { return this._columns; } // set the columns from an array of column definitions. // Note: any headers defined will overwrite existing values. , set: function set(value) { var _this = this; // calculate max header row count this._headerRowCount = value.reduce(function (pv, cv) { var headerCount = cv.header && 1 || cv.headers && cv.headers.length || 0; return Math.max(pv, headerCount); }, 0); // construct Column objects var count = 1; var columns = this._columns = []; value.forEach(function (defn) { var column = new Column(_this, count++, false); columns.push(column); column.defn = defn; }); } }, { key: "getColumnKey", value: function getColumnKey(key) { return this._keys[key]; } }, { key: "setColumnKey", value: function setColumnKey(key, value) { this._keys[key] = value; } }, { key: "deleteColumnKey", value: function deleteColumnKey(key) { delete this._keys[key]; } }, { key: "eachColumnKey", value: function eachColumnKey(f) { _.each(this._keys, f); } // get a single column by col number. If it doesn't exist, it and any gaps before it // are created. }, { key: "getColumn", value: function getColumn(c) { if (typeof c === 'string') { // if it matches a key'd column, return that var col = this._keys[c]; if (col) return col; // otherwise, assume letter c = colCache.l2n(c); } if (!this._columns) { this._columns = []; } if (c > this._columns.length) { var n = this._columns.length + 1; while (n <= c) { this._columns.push(new Column(this, n++)); } } return this._columns[c - 1]; } // ========================================================================= // Rows }, { key: "_nextRow", get: function get() { return this._rowZero + this._rows.length; } // iterate over every uncommitted row in the worksheet, including maybe empty rows }, { key: "eachRow", value: function eachRow(options, iteratee) { if (!iteratee) { iteratee = options; options = undefined; } if (options && options.includeEmpty) { var n = this._nextRow; for (var i = this._rowZero; i < n; i++) { iteratee(this.getRow(i), i); } } else { this._rows.forEach(function (row) { if (row.hasValues) { iteratee(row, row.number); } }); } } }, { key: "_commitRow", value: function () { var _commitRow2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(cRow) { var found, row; return _regeneratorRuntime().wrap(function _callee2$(_context2) { while (1) switch (_context2.prev = _context2.next) { case 0: // since rows must be written in order, we commit all rows up till and including cRow found = false; case 1: if (!(this._rows.length && !found)) { _context2.next = 11; break; } row = this._rows.shift(); this._rowZero++; if (!row) { _context2.next = 9; break; } _context2.next = 7; return this._writeRow(row); case 7: found = row.number === cRow.number; this._rowZero = row.number + 1; case 9: _context2.next = 1; break; case 11: case "end": return _context2.stop(); } }, _callee2, this); })); function _commitRow(_x) { return _commitRow2.apply(this, arguments); } return _commitRow; }() }, { key: "lastRow", get: function get() { // returns last uncommitted row if (this._rows.length) { return this._rows[this._rows.length - 1]; } return undefined; } // find a row (if exists) by row number }, { key: "findRow", value: function findRow(rowNumber) { var index = rowNumber - this._rowZero; return this._rows[index]; } }, { key: "getRow", value: function getRow(rowNumber) { var index = rowNumber - this._rowZero; // may fail if rows have been comitted if (index < 0) { throw new Error('Out of bounds: this row has been committed'); } var row = this._rows[index]; if (!row) { this._rows[index] = row = new Row(this, rowNumber); } return row; } }, { key: "addRow", value: function addRow(value) { var row = new Row(this, this._nextRow); this._rows[row.number - this._rowZero] = row; row.values = value; return row; } // ================================================================================ // Cells // returns the cell at [r,c] or address given by r. If not found, return undefined }, { key: "findCell", value: function findCell(r, c) { var address = colCache.getAddress(r, c); var row = this.findRow(address.row); return row ? row.findCell(address.column) : undefined; } // return the cell at [r,c] or address given by r. If not found, create a new one. }, { key: "getCell", value: function getCell(r, c) { var address = colCache.getAddress(r, c); var row = this.getRow(address.row); return row.getCellEx(address); } }, { key: "mergeCells", value: function mergeCells() { for (var _len = arguments.length, cells = new Array(_len), _key = 0; _key < _len; _key++) { cells[_key] = arguments[_key]; } // may fail if rows have been comitted var dimensions = new Dimensions(cells); // check cells aren't already merged this._merges.forEach(function (merge) { if (merge.intersects(dimensions)) { throw new Error('Cannot merge already merged cells'); } }); // apply merge var master = this.getCell(dimensions.top, dimensions.left); for (var i = dimensions.top; i <= dimensions.bottom; i++) { for (var j = dimensions.left; j <= dimensions.right; j++) { if (i > dimensions.top || j > dimensions.left) { this.getCell(i, j).merge(master); } } } // index merge this._merges.push(dimensions); } // =========================================================================== // Conditional Formatting }, { key: "addConditionalFormatting", value: function addConditionalFormatting(cf) { this.conditionalFormatting.push(cf); } }, { key: "removeConditionalFormatting", value: function removeConditionalFormatting(filter) { if (typeof filter === 'number') { this.conditionalFormatting.splice(filter, 1); } else if (filter instanceof Function) { this.conditionalFormatting = this.conditionalFormatting.filter(filter); } else { this.conditionalFormatting = []; } } // ========================================================================= }, { key: "addBackgroundImage", value: function addBackgroundImage(imageId) { this._background = { imageId: imageId }; } }, { key: "getBackgroundImageId", value: function getBackgroundImageId() { return this._background && this._background.imageId; } // ========================================================================= // Worksheet Protection }, { key: "protect", value: function protect(password, options) { var _this2 = this; // TODO: make this function truly async // perhaps marshal to worker thread or something return new Promise(function (resolve) { _this2.sheetProtection = { sheet: true }; if (options && 'spinCount' in options) { // force spinCount to be integer >= 0 options.spinCount = Number.isFinite(options.spinCount) ? Math.round(Math.max(0, options.spinCount)) : 100000; } if (password) { _this2.sheetProtection.algorithmName = 'SHA-512'; _this2.sheetProtection.saltValue = Encryptor.randomBytes(16).toString('base64'); _this2.sheetProtection.spinCount = options && 'spinCount' in options ? options.spinCount : 100000; // allow user specified spinCount _this2.sheetProtection.hashValue = Encryptor.convertPasswordToHash(password, 'SHA512', _this2.sheetProtection.saltValue, _this2.sheetProtection.spinCount); } if (options) { _this2.sheetProtection = Object.assign(_this2.sheetProtection, options); if (!password && 'spinCount' in options) { delete _this2.sheetProtection.spinCount; } } resolve(); }); } }, { key: "unprotect", value: function unprotect() { this.sheetProtection = null; } // ================================================================================ }, { key: "_write", value: function _write(text) { xmlBuffer.reset(); xmlBuffer.addText(text); this.stream.write(xmlBuffer); } }, { key: "_writeSheetProperties", value: function _writeSheetProperties(xmlBuf, properties, pageSetup) { var sheetPropertiesModel = { outlineProperties: properties && properties.outlineProperties, tabColor: properties && properties.tabColor, pageSetup: pageSetup && pageSetup.fitToPage ? { fitToPage: pageSetup.fitToPage } : undefined }; xmlBuf.addText(xform.sheetProperties.toXml(sheetPropertiesModel)); } }, { key: "_writeSheetFormatProperties", value: function _writeSheetFormatProperties(xmlBuf, properties) { var sheetFormatPropertiesModel = properties ? { defaultRowHeight: properties.defaultRowHeight, dyDescent: properties.dyDescent, outlineLevelCol: properties.outlineLevelCol, outlineLevelRow: properties.outlineLevelRow } : undefined; if (properties.defaultColWidth) { sheetFormatPropertiesModel.defaultColWidth = properties.defaultColWidth; } xmlBuf.addText(xform.sheetFormatProperties.toXml(sheetFormatPropertiesModel)); } }, { key: "_writeOpenWorksheet", value: function _writeOpenWorksheet() { xmlBuffer.reset(); xmlBuffer.addText('<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'); xmlBuffer.addText('<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"' + ' xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"' + ' xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"' + ' mc:Ignorable="x14ac"' + ' xmlns:x14ac="http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac">'); this._writeSheetProperties(xmlBuffer, this.properties, this.pageSetup); xmlBuffer.addText(xform.sheetViews.toXml(this.views)); this._writeSheetFormatProperties(xmlBuffer, this.properties); this.stream.write(xmlBuffer); } }, { key: "_writeColumns", value: function _writeColumns() { var cols = Column.toModel(this.columns); if (cols) { xform.columns.prepare(cols, { styles: this._workbook.styles }); this.stream.write(xform.columns.toXml(cols)); } } }, { key: "_writeOpenSheetData", value: function _writeOpenSheetData() { this._write('<sheetData>'); } }, { key: "_writeRow", value: function () { var _writeRow2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(row) { var model, options; return _regeneratorRuntime().wrap(function _callee3$(_context3) { while (1) switch (_context3.prev = _context3.next) { case 0: if (!this.startedData) { this._writeColumns(); this._writeOpenSheetData(); this.startedData = true; } if (!(row.hasValues || row.height)) { _context3.next = 8; break; } model = row.model; options = { styles: this._workbook.styles, sharedStrings: this.useSharedStrings ? this._workbook.sharedStrings : undefined, hyperlinks: this._sheetRelsWriter.hyperlinksProxy, merges: this._merges, formulae: this._formulae, siFormulae: this._siFormulae, comments: [] }; xform.row.prepare(model, options); _context3.next = 7; return this.stream.write(xform.row.toXml(model)); case 7: if (options.comments.length) { this.hasComments = true; this._sheetCommentsWriter.addComments(options.comments); } case 8: case "end": return _context3.stop(); } }, _callee3, this); })); function _writeRow(_x2) { return _writeRow2.apply(this, arguments); } return _writeRow; }() }, { key: "_writeCloseSheetData", value: function _writeCloseSheetData() { this._write('</sheetData>'); } }, { key: "_writeMergeCells", value: function _writeMergeCells() { if (this._merges.length) { xmlBuffer.reset(); xmlBuffer.addText("<mergeCells count=\"".concat(this._merges.length, "\">")); this._merges.forEach(function (merge) { xmlBuffer.addText("<mergeCell ref=\"".concat(merge, "\"/>")); }); xmlBuffer.addText('</mergeCells>'); this.stream.write(xmlBuffer); } } }, { key: "_writeHyperlinks", value: function _writeHyperlinks() { // eslint-disable-next-line no-underscore-dangle this.stream.write(xform.hyperlinks.toXml(this._sheetRelsWriter._hyperlinks)); } }, { key: "_writeConditionalFormatting", value: function _writeConditionalFormatting() { var options = { styles: this._workbook.styles }; xform.conditionalFormattings.prepare(this.conditionalFormatting, options); this.stream.write(xform.conditionalFormattings.toXml(this.conditionalFormatting)); } }, { key: "_writeRowBreaks", value: function _writeRowBreaks() { this.stream.write(xform.rowBreaks.toXml(this.rowBreaks)); } }, { key: "_writeDataValidations", value: function _writeDataValidations() { this.stream.write(xform.dataValidations.toXml(this.dataValidations.model)); } }, { key: "_writeSheetProtection", value: function _writeSheetProtection() { this.stream.write(xform.sheetProtection.toXml(this.sheetProtection)); } }, { key: "_writePageMargins", value: function _writePageMargins() { this.stream.write(xform.pageMargins.toXml(this.pageSetup.margins)); } }, { key: "_writePageSetup", value: function _writePageSetup() { this.stream.write(xform.pageSeteup.toXml(this.pageSetup)); } }, { key: "_writeHeaderFooter", value: function _writeHeaderFooter() { this.stream.write(xform.headerFooter.toXml(this.headerFooter)); } }, { key: "_writeAutoFilter", value: function _writeAutoFilter() { this.stream.write(xform.autoFilter.toXml(this.autoFilter)); } }, { key: "_writeBackground", value: function _writeBackground() { if (this._background) { if (this._background.imageId !== undefined) { var image = this._workbook.getImage(this._background.imageId); var pictureId = this._sheetRelsWriter.addMedia({ Target: "../media/".concat(image.name), Type: RelType.Image }); this._background = _objectSpread(_objectSpread({}, this._background), {}, { rId: pictureId }); } this.stream.write(xform.picture.toXml({ rId: this._background.rId })); } } }, { key: "_writeLegacyData", value: function _writeLegacyData() { if (this.hasComments) { xmlBuffer.reset(); xmlBuffer.addText("<legacyDrawing r:id=\"".concat(this._sheetCommentsWriter.vmlRelId, "\"/>")); this.stream.write(xmlBuffer); } } }, { key: "_writeDimensions", value: function _writeDimensions() { // for some reason, Excel can't handle dimensions at the bottom of the file // and we don't know the dimensions until the commit, so don't write them. // this._write('<dimension ref="' + this._dimensions + '"/>'); } }, { key: "_writeCloseWorksheet", value: function _writeCloseWorksheet() { this._write('</worksheet>'); } }]); return WorksheetWriter; }(); module.exports = WorksheetWriter; //# sourceMappingURL=worksheet-writer.js.map