@zlooun/exceljs
Version:
Fixes the problem with writing a file using streams and not using RAM based on 'exeljs'
1,214 lines (1,190 loc) • 2.69 MB
JavaScript
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.ExcelJS = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
"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 _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 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 fs = require('fs');
var fastCsv = require('fast-csv');
var customParseFormat = require('dayjs/plugin/customParseFormat');
var utc = require('dayjs/plugin/utc');
var dayjs = require('dayjs').extend(customParseFormat).extend(utc);
var StreamBuf = require('../utils/stream-buf');
var _require = require('../utils/utils'),
exists = _require.fs.exists;
/* eslint-disable quote-props */
var SpecialValues = {
true: true,
false: false,
'#N/A': {
error: '#N/A'
},
'#REF!': {
error: '#REF!'
},
'#NAME?': {
error: '#NAME?'
},
'#DIV/0!': {
error: '#DIV/0!'
},
'#NULL!': {
error: '#NULL!'
},
'#VALUE!': {
error: '#VALUE!'
},
'#NUM!': {
error: '#NUM!'
}
};
/* eslint-ensable quote-props */
var CSV = /*#__PURE__*/function () {
function CSV(workbook) {
_classCallCheck(this, CSV);
this.workbook = workbook;
this.worksheet = null;
}
_createClass(CSV, [{
key: "readFile",
value: function () {
var _readFile = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(filename, options) {
var stream, worksheet;
return _regeneratorRuntime().wrap(function _callee$(_context) {
while (1) switch (_context.prev = _context.next) {
case 0:
options = options || {};
_context.next = 3;
return exists(filename);
case 3:
if (_context.sent) {
_context.next = 5;
break;
}
throw new Error("File not found: ".concat(filename));
case 5:
stream = fs.createReadStream(filename);
_context.next = 8;
return this.read(stream, options);
case 8:
worksheet = _context.sent;
stream.close();
return _context.abrupt("return", worksheet);
case 11:
case "end":
return _context.stop();
}
}, _callee, this);
}));
function readFile(_x, _x2) {
return _readFile.apply(this, arguments);
}
return readFile;
}()
}, {
key: "read",
value: function read(stream, options) {
var _this = this;
options = options || {};
return new Promise(function (resolve, reject) {
var worksheet = _this.workbook.addWorksheet(options.sheetName);
var dateFormats = options.dateFormats || ['YYYY-MM-DD[T]HH:mm:ssZ', 'YYYY-MM-DD[T]HH:mm:ss', 'MM-DD-YYYY', 'YYYY-MM-DD'];
var map = options.map || function (datum) {
if (datum === '') {
return null;
}
var datumNumber = Number(datum);
if (!Number.isNaN(datumNumber) && datumNumber !== Infinity) {
return datumNumber;
}
var dt = dateFormats.reduce(function (matchingDate, currentDateFormat) {
if (matchingDate) {
return matchingDate;
}
var dayjsObj = dayjs(datum, currentDateFormat, true);
if (dayjsObj.isValid()) {
return dayjsObj;
}
return null;
}, null);
if (dt) {
return new Date(dt.valueOf());
}
var special = SpecialValues[datum];
if (special !== undefined) {
return special;
}
return datum;
};
var csvStream = fastCsv.parse(options.parserOptions).on('data', function (data) {
worksheet.addRow(data.map(map));
}).on('end', function () {
csvStream.emit('worksheet', worksheet);
});
csvStream.on('worksheet', resolve).on('error', reject);
stream.pipe(csvStream);
});
}
/**
* @deprecated since version 4.0. You should use `CSV#read` instead. Please follow upgrade instruction: https://github.com/exceljs/exceljs/blob/master/UPGRADE-4.0.md
*/
}, {
key: "createInputStream",
value: function createInputStream() {
throw new Error('`CSV#createInputStream` is deprecated. You should use `CSV#read` instead. This method will be removed in version 5.0. Please follow upgrade instruction: https://github.com/exceljs/exceljs/blob/master/UPGRADE-4.0.md');
}
}, {
key: "write",
value: function write(stream, options) {
var _this2 = this;
return new Promise(function (resolve, reject) {
options = options || {};
// const encoding = options.encoding || 'utf8';
// const separator = options.separator || ',';
// const quoteChar = options.quoteChar || '\'';
var worksheet = _this2.workbook.getWorksheet(options.sheetName || options.sheetId);
var csvStream = fastCsv.format(options.formatterOptions);
stream.on('finish', function () {
resolve();
});
csvStream.on('error', reject);
csvStream.pipe(stream);
var _options = options,
dateFormat = _options.dateFormat,
dateUTC = _options.dateUTC;
var map = options.map || function (value) {
if (value) {
if (value.text || value.hyperlink) {
return value.hyperlink || value.text || '';
}
if (value.formula || value.result) {
return value.result || '';
}
if (value instanceof Date) {
if (dateFormat) {
return dateUTC ? dayjs.utc(value).format(dateFormat) : dayjs(value).format(dateFormat);
}
return dateUTC ? dayjs.utc(value).format() : dayjs(value).format();
}
if (value.error) {
return value.error;
}
if (_typeof(value) === 'object') {
return JSON.stringify(value);
}
}
return value;
};
var includeEmptyRows = options.includeEmptyRows === undefined || options.includeEmptyRows;
var lastRow = 1;
if (worksheet) {
worksheet.eachRow(function (row, rowNumber) {
if (includeEmptyRows) {
while (lastRow++ < rowNumber - 1) {
csvStream.write([]);
}
}
var values = row.values;
values.shift();
csvStream.write(values.map(map));
lastRow = rowNumber;
});
}
csvStream.end();
});
}
}, {
key: "writeFile",
value: function writeFile(filename, options) {
options = options || {};
var streamOptions = {
encoding: options.encoding || 'utf8'
};
var stream = fs.createWriteStream(filename, streamOptions);
return this.write(stream, options);
}
}, {
key: "writeBuffer",
value: function () {
var _writeBuffer = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(options) {
var stream;
return _regeneratorRuntime().wrap(function _callee2$(_context2) {
while (1) switch (_context2.prev = _context2.next) {
case 0:
stream = new StreamBuf();
_context2.next = 3;
return this.write(stream, options);
case 3:
return _context2.abrupt("return", stream.read());
case 4:
case "end":
return _context2.stop();
}
}, _callee2, this);
}));
function writeBuffer(_x3) {
return _writeBuffer.apply(this, arguments);
}
return writeBuffer;
}()
}]);
return CSV;
}();
module.exports = CSV;
},{"../utils/stream-buf":24,"../utils/utils":27,"dayjs":390,"dayjs/plugin/customParseFormat":391,"dayjs/plugin/utc":392,"fast-csv":423,"fs":216}],2:[function(require,module,exports){
'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 _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 colCache = require('../utils/col-cache');
var Anchor = /*#__PURE__*/function () {
function Anchor(worksheet, address) {
var offset = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
_classCallCheck(this, Anchor);
if (!address) {
this.nativeCol = 0;
this.nativeColOff = 0;
this.nativeRow = 0;
this.nativeRowOff = 0;
} else if (typeof address === 'string') {
var decoded = colCache.decodeAddress(address);
this.nativeCol = decoded.col + offset;
this.nativeColOff = 0;
this.nativeRow = decoded.row + offset;
this.nativeRowOff = 0;
} else if (address.nativeCol !== undefined) {
this.nativeCol = address.nativeCol || 0;
this.nativeColOff = address.nativeColOff || 0;
this.nativeRow = address.nativeRow || 0;
this.nativeRowOff = address.nativeRowOff || 0;
} else if (address.col !== undefined) {
this.col = address.col + offset;
this.row = address.row + offset;
} else {
this.nativeCol = 0;
this.nativeColOff = 0;
this.nativeRow = 0;
this.nativeRowOff = 0;
}
this.worksheet = worksheet;
}
_createClass(Anchor, [{
key: "col",
get: function get() {
return this.nativeCol + Math.min(this.colWidth - 1, this.nativeColOff) / this.colWidth;
},
set: function set(v) {
this.nativeCol = Math.floor(v);
this.nativeColOff = Math.floor((v - this.nativeCol) * this.colWidth);
}
}, {
key: "row",
get: function get() {
return this.nativeRow + Math.min(this.rowHeight - 1, this.nativeRowOff) / this.rowHeight;
},
set: function set(v) {
this.nativeRow = Math.floor(v);
this.nativeRowOff = Math.floor((v - this.nativeRow) * this.rowHeight);
}
}, {
key: "colWidth",
get: function get() {
return this.worksheet && this.worksheet.getColumn(this.nativeCol + 1) && this.worksheet.getColumn(this.nativeCol + 1).isCustomWidth ? Math.floor(this.worksheet.getColumn(this.nativeCol + 1).width * 10000) : 640000;
}
}, {
key: "rowHeight",
get: function get() {
return this.worksheet && this.worksheet.getRow(this.nativeRow + 1) && this.worksheet.getRow(this.nativeRow + 1).height ? Math.floor(this.worksheet.getRow(this.nativeRow + 1).height * 10000) : 180000;
}
}, {
key: "model",
get: function get() {
return {
nativeCol: this.nativeCol,
nativeColOff: this.nativeColOff,
nativeRow: this.nativeRow,
nativeRowOff: this.nativeRowOff
};
},
set: function set(value) {
this.nativeCol = value.nativeCol;
this.nativeColOff = value.nativeColOff;
this.nativeRow = value.nativeRow;
this.nativeRowOff = value.nativeRowOff;
}
}], [{
key: "asInstance",
value: function asInstance(model) {
return model instanceof Anchor || model == null ? model : new Anchor(model);
}
}]);
return Anchor;
}();
module.exports = Anchor;
},{"../utils/col-cache":19}],3:[function(require,module,exports){
"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 _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); }
/* eslint-disable max-classes-per-file */
var colCache = require('../utils/col-cache');
var _ = require('../utils/under-dash');
var Enums = require('./enums');
var _require = require('../utils/shared-formula'),
slideFormula = _require.slideFormula;
var Note = require('./note');
// Cell requirements
// Operate inside a worksheet
// Store and retrieve a value with a range of types: text, number, date, hyperlink, reference, formula, etc.
// Manage/use and manipulate cell format either as local to cell or inherited from column or row.
var Cell = /*#__PURE__*/function () {
function Cell(row, column, address) {
_classCallCheck(this, Cell);
if (!row || !column) {
throw new Error('A Cell needs a Row');
}
this._row = row;
this._column = column;
colCache.validateAddress(address);
this._address = address;
// TODO: lazy evaluation of this._value
this._value = Value.create(Cell.Types.Null, this);
this.style = this._mergeStyle(row.style, column.style, {});
this._mergeCount = 0;
}
_createClass(Cell, [{
key: "worksheet",
get: function get() {
return this._row.worksheet;
}
}, {
key: "workbook",
get: function get() {
return this._row.worksheet.workbook;
}
// help GC by removing cyclic (and other) references
}, {
key: "destroy",
value: function destroy() {
delete this.style;
delete this._value;
delete this._row;
delete this._column;
delete this._address;
}
// =========================================================================
// Styles stuff
}, {
key: "numFmt",
get: function get() {
return this.style.numFmt;
},
set: function set(value) {
this.style.numFmt = value;
}
}, {
key: "font",
get: function get() {
return this.style.font;
},
set: function set(value) {
this.style.font = value;
}
}, {
key: "alignment",
get: function get() {
return this.style.alignment;
},
set: function set(value) {
this.style.alignment = value;
}
}, {
key: "border",
get: function get() {
return this.style.border;
},
set: function set(value) {
this.style.border = value;
}
}, {
key: "fill",
get: function get() {
return this.style.fill;
},
set: function set(value) {
this.style.fill = value;
}
}, {
key: "protection",
get: function get() {
return this.style.protection;
},
set: function set(value) {
this.style.protection = value;
}
}, {
key: "_mergeStyle",
value: function _mergeStyle(rowStyle, colStyle, style) {
var numFmt = rowStyle && rowStyle.numFmt || colStyle && colStyle.numFmt;
if (numFmt) style.numFmt = numFmt;
var font = rowStyle && rowStyle.font || colStyle && colStyle.font;
if (font) style.font = font;
var alignment = rowStyle && rowStyle.alignment || colStyle && colStyle.alignment;
if (alignment) style.alignment = alignment;
var border = rowStyle && rowStyle.border || colStyle && colStyle.border;
if (border) style.border = border;
var fill = rowStyle && rowStyle.fill || colStyle && colStyle.fill;
if (fill) style.fill = fill;
var protection = rowStyle && rowStyle.protection || colStyle && colStyle.protection;
if (protection) style.protection = protection;
return style;
}
// =========================================================================
// return the address for this cell
}, {
key: "address",
get: function get() {
return this._address;
}
}, {
key: "row",
get: function get() {
return this._row.number;
}
}, {
key: "col",
get: function get() {
return this._column.number;
}
}, {
key: "$col$row",
get: function get() {
return "$".concat(this._column.letter, "$").concat(this.row);
}
// =========================================================================
// Value stuff
}, {
key: "type",
get: function get() {
return this._value.type;
}
}, {
key: "effectiveType",
get: function get() {
return this._value.effectiveType;
}
}, {
key: "toCsvString",
value: function toCsvString() {
return this._value.toCsvString();
}
// =========================================================================
// Merge stuff
}, {
key: "addMergeRef",
value: function addMergeRef() {
this._mergeCount++;
}
}, {
key: "releaseMergeRef",
value: function releaseMergeRef() {
this._mergeCount--;
}
}, {
key: "isMerged",
get: function get() {
return this._mergeCount > 0 || this.type === Cell.Types.Merge;
}
}, {
key: "merge",
value: function merge(master, ignoreStyle) {
this._value.release();
this._value = Value.create(Cell.Types.Merge, this, master);
if (!ignoreStyle) {
this.style = master.style;
}
}
}, {
key: "unmerge",
value: function unmerge() {
if (this.type === Cell.Types.Merge) {
this._value.release();
this._value = Value.create(Cell.Types.Null, this);
this.style = this._mergeStyle(this._row.style, this._column.style, {});
}
}
}, {
key: "isMergedTo",
value: function isMergedTo(master) {
if (this._value.type !== Cell.Types.Merge) return false;
return this._value.isMergedTo(master);
}
}, {
key: "master",
get: function get() {
if (this.type === Cell.Types.Merge) {
return this._value.master;
}
return this; // an unmerged cell is its own master
}
}, {
key: "isHyperlink",
get: function get() {
return this._value.type === Cell.Types.Hyperlink;
}
}, {
key: "hyperlink",
get: function get() {
return this._value.hyperlink;
}
// return the value
}, {
key: "value",
get: function get() {
return this._value.value;
}
// set the value - can be number, string or raw
,
set: function set(v) {
// special case - merge cells set their master's value
if (this.type === Cell.Types.Merge) {
this._value.master.value = v;
return;
}
this._value.release();
// assign value
this._value = Value.create(Value.getType(v), this, v);
}
}, {
key: "note",
get: function get() {
return this._comment && this._comment.note;
},
set: function set(note) {
this._comment = new Note(note);
}
}, {
key: "text",
get: function get() {
return this._value.toString();
}
}, {
key: "html",
get: function get() {
return _.escapeHtml(this.text);
}
}, {
key: "toString",
value: function toString() {
return this.text;
}
}, {
key: "_upgradeToHyperlink",
value: function _upgradeToHyperlink(hyperlink) {
// if this cell is a string, turn it into a Hyperlink
if (this.type === Cell.Types.String) {
this._value = Value.create(Cell.Types.Hyperlink, this, {
text: this._value.value,
hyperlink: hyperlink
});
}
}
// =========================================================================
// Formula stuff
}, {
key: "formula",
get: function get() {
return this._value.formula;
}
}, {
key: "result",
get: function get() {
return this._value.result;
}
}, {
key: "formulaType",
get: function get() {
return this._value.formulaType;
}
// =========================================================================
// Name stuff
}, {
key: "fullAddress",
get: function get() {
var worksheet = this._row.worksheet;
return {
sheetName: worksheet.name,
address: this.address,
row: this.row,
col: this.col
};
}
}, {
key: "name",
get: function get() {
return this.names[0];
},
set: function set(value) {
this.names = [value];
}
}, {
key: "names",
get: function get() {
return this.workbook.definedNames.getNamesEx(this.fullAddress);
},
set: function set(value) {
var _this = this;
var definedNames = this.workbook.definedNames;
definedNames.removeAllNames(this.fullAddress);
value.forEach(function (name) {
definedNames.addEx(_this.fullAddress, name);
});
}
}, {
key: "addName",
value: function addName(name) {
this.workbook.definedNames.addEx(this.fullAddress, name);
}
}, {
key: "removeName",
value: function removeName(name) {
this.workbook.definedNames.removeEx(this.fullAddress, name);
}
}, {
key: "removeAllNames",
value: function removeAllNames() {
this.workbook.definedNames.removeAllNames(this.fullAddress);
}
// =========================================================================
// Data Validation stuff
}, {
key: "_dataValidations",
get: function get() {
return this.worksheet.dataValidations;
}
}, {
key: "dataValidation",
get: function get() {
return this._dataValidations.find(this.address);
},
set: function set(value) {
this._dataValidations.add(this.address, value);
}
// =========================================================================
// Model stuff
}, {
key: "model",
get: function get() {
var model = this._value.model;
model.style = this.style;
if (this._comment) {
model.comment = this._comment.model;
}
return model;
},
set: function set(value) {
this._value.release();
this._value = Value.create(value.type, this);
this._value.model = value;
if (value.comment) {
switch (value.comment.type) {
case 'note':
this._comment = Note.fromModel(value.comment);
break;
}
}
if (value.style) {
this.style = value.style;
} else {
this.style = {};
}
}
}]);
return Cell;
}();
Cell.Types = Enums.ValueType;
// =============================================================================
// Internal Value Types
var NullValue = /*#__PURE__*/function () {
function NullValue(cell) {
_classCallCheck(this, NullValue);
this.model = {
address: cell.address,
type: Cell.Types.Null
};
}
_createClass(NullValue, [{
key: "value",
get: function get() {
return null;
},
set: function set(value) {
// nothing to do
}
}, {
key: "type",
get: function get() {
return Cell.Types.Null;
}
}, {
key: "effectiveType",
get: function get() {
return Cell.Types.Null;
}
}, {
key: "address",
get: function get() {
return this.model.address;
},
set: function set(value) {
this.model.address = value;
}
}, {
key: "toCsvString",
value: function toCsvString() {
return '';
}
}, {
key: "release",
value: function release() {}
}, {
key: "toString",
value: function toString() {
return '';
}
}]);
return NullValue;
}();
var NumberValue = /*#__PURE__*/function () {
function NumberValue(cell, value) {
_classCallCheck(this, NumberValue);
this.model = {
address: cell.address,
type: Cell.Types.Number,
value: value
};
}
_createClass(NumberValue, [{
key: "value",
get: function get() {
return this.model.value;
},
set: function set(value) {
this.model.value = value;
}
}, {
key: "type",
get: function get() {
return Cell.Types.Number;
}
}, {
key: "effectiveType",
get: function get() {
return Cell.Types.Number;
}
}, {
key: "address",
get: function get() {
return this.model.address;
},
set: function set(value) {
this.model.address = value;
}
}, {
key: "toCsvString",
value: function toCsvString() {
return this.model.value.toString();
}
}, {
key: "release",
value: function release() {}
}, {
key: "toString",
value: function toString() {
return this.model.value.toString();
}
}]);
return NumberValue;
}();
var StringValue = /*#__PURE__*/function () {
function StringValue(cell, value) {
_classCallCheck(this, StringValue);
this.model = {
address: cell.address,
type: Cell.Types.String,
value: value
};
}
_createClass(StringValue, [{
key: "value",
get: function get() {
return this.model.value;
},
set: function set(value) {
this.model.value = value;
}
}, {
key: "type",
get: function get() {
return Cell.Types.String;
}
}, {
key: "effectiveType",
get: function get() {
return Cell.Types.String;
}
}, {
key: "address",
get: function get() {
return this.model.address;
},
set: function set(value) {
this.model.address = value;
}
}, {
key: "toCsvString",
value: function toCsvString() {
return "\"".concat(this.model.value.replace(/"/g, '""'), "\"");
}
}, {
key: "release",
value: function release() {}
}, {
key: "toString",
value: function toString() {
return this.model.value;
}
}]);
return StringValue;
}();
var RichTextValue = /*#__PURE__*/function () {
function RichTextValue(cell, value) {
_classCallCheck(this, RichTextValue);
this.model = {
address: cell.address,
type: Cell.Types.String,
value: value
};
}
_createClass(RichTextValue, [{
key: "value",
get: function get() {
return this.model.value;
},
set: function set(value) {
this.model.value = value;
}
}, {
key: "toString",
value: function toString() {
return this.model.value.richText.map(function (t) {
return t.text;
}).join('');
}
}, {
key: "type",
get: function get() {
return Cell.Types.RichText;
}
}, {
key: "effectiveType",
get: function get() {
return Cell.Types.RichText;
}
}, {
key: "address",
get: function get() {
return this.model.address;
},
set: function set(value) {
this.model.address = value;
}
}, {
key: "toCsvString",
value: function toCsvString() {
return "\"".concat(this.text.replace(/"/g, '""'), "\"");
}
}, {
key: "release",
value: function release() {}
}]);
return RichTextValue;
}();
var DateValue = /*#__PURE__*/function () {
function DateValue(cell, value) {
_classCallCheck(this, DateValue);
this.model = {
address: cell.address,
type: Cell.Types.Date,
value: value
};
}
_createClass(DateValue, [{
key: "value",
get: function get() {
return this.model.value;
},
set: function set(value) {
this.model.value = value;
}
}, {
key: "type",
get: function get() {
return Cell.Types.Date;
}
}, {
key: "effectiveType",
get: function get() {
return Cell.Types.Date;
}
}, {
key: "address",
get: function get() {
return this.model.address;
},
set: function set(value) {
this.model.address = value;
}
}, {
key: "toCsvString",
value: function toCsvString() {
return this.model.value.toISOString();
}
}, {
key: "release",
value: function release() {}
}, {
key: "toString",
value: function toString() {
return this.model.value.toString();
}
}]);
return DateValue;
}();
var HyperlinkValue = /*#__PURE__*/function () {
function HyperlinkValue(cell, value) {
_classCallCheck(this, HyperlinkValue);
this.model = {
address: cell.address,
type: Cell.Types.Hyperlink,
text: value ? value.text : undefined,
hyperlink: value ? value.hyperlink : undefined
};
if (value && value.tooltip) {
this.model.tooltip = value.tooltip;
}
}
_createClass(HyperlinkValue, [{
key: "value",
get: function get() {
var v = {
text: this.model.text,
hyperlink: this.model.hyperlink
};
if (this.model.tooltip) {
v.tooltip = this.model.tooltip;
}
return v;
},
set: function set(value) {
this.model = {
text: value.text,
hyperlink: value.hyperlink
};
if (value.tooltip) {
this.model.tooltip = value.tooltip;
}
}
}, {
key: "text",
get: function get() {
return this.model.text;
},
set: function set(value) {
this.model.text = value;
}
/*
get tooltip() {
return this.model.tooltip;
}
set tooltip(value) {
this.model.tooltip = value;
} */
}, {
key: "hyperlink",
get: function get() {
return this.model.hyperlink;
},
set: function set(value) {
this.model.hyperlink = value;
}
}, {
key: "type",
get: function get() {
return Cell.Types.Hyperlink;
}
}, {
key: "effectiveType",
get: function get() {
return Cell.Types.Hyperlink;
}
}, {
key: "address",
get: function get() {
return this.model.address;
},
set: function set(value) {
this.model.address = value;
}
}, {
key: "toCsvString",
value: function toCsvString() {
return this.model.hyperlink;
}
}, {
key: "release",
value: function release() {}
}, {
key: "toString",
value: function toString() {
return this.model.text;
}
}]);
return HyperlinkValue;
}();
var MergeValue = /*#__PURE__*/function () {
function MergeValue(cell, master) {
_classCallCheck(this, MergeValue);
this.model = {
address: cell.address,
type: Cell.Types.Merge,
master: master ? master.address : undefined
};
this._master = master;
if (master) {
master.addMergeRef();
}
}
_createClass(MergeValue, [{
key: "value",
get: function get() {
return this._master.value;
},
set: function set(value) {
if (value instanceof Cell) {
if (this._master) {
this._master.releaseMergeRef();
}
value.addMergeRef();
this._master = value;
} else {
this._master.value = value;
}
}
}, {
key: "isMergedTo",
value: function isMergedTo(master) {
return master === this._master;
}
}, {
key: "master",
get: function get() {
return this._master;
}
}, {
key: "type",
get: function get() {
return Cell.Types.Merge;
}
}, {
key: "effectiveType",
get: function get() {
return this._master.effectiveType;
}
}, {
key: "address",
get: function get() {
return this.model.address;
},
set: function set(value) {
this.model.address = value;
}
}, {
key: "toCsvString",
value: function toCsvString() {
return '';
}
}, {
key: "release",
value: function release() {
this._master.releaseMergeRef();
}
}, {
key: "toString",
value: function toString() {
return this.value.toString();
}
}]);
return MergeValue;
}();
var FormulaValue = /*#__PURE__*/function () {
function FormulaValue(cell, value) {
_classCallCheck(this, FormulaValue);
this.cell = cell;
this.model = {
address: cell.address,
type: Cell.Types.Formula,
shareType: value ? value.shareType : undefined,
ref: value ? value.ref : undefined,
formula: value ? value.formula : undefined,
sharedFormula: value ? value.sharedFormula : undefined,
result: value ? value.result : undefined
};
}
_createClass(FormulaValue, [{
key: "_copyModel",
value: function _copyModel(model) {
var copy = {};
var cp = function cp(name) {
var value = model[name];
if (value) {
copy[name] = value;
}
};
cp('formula');
cp('result');
cp('ref');
cp('shareType');
cp('sharedFormula');
return copy;
}
}, {
key: "value",
get: function get() {
return this._copyModel(this.model);
},
set: function set(value) {
this.model = this._copyModel(value);
}
}, {
key: "validate",
value: function validate(value) {
switch (Value.getType(value)) {
case Cell.Types.Null:
case Cell.Types.String:
case Cell.Types.Number:
case Cell.Types.Date:
break;
case Cell.Types.Hyperlink:
case Cell.Types.Formula: