worksheet.js 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900
  1. "use strict";
  2. const _ = require('../utils/under-dash');
  3. const colCache = require('../utils/col-cache');
  4. const Range = require('./range');
  5. const Row = require('./row');
  6. const Column = require('./column');
  7. const Enums = require('./enums');
  8. const Image = require('./image');
  9. const Table = require('./table');
  10. const DataValidations = require('./data-validations');
  11. const Encryptor = require('../utils/encryptor');
  12. const {
  13. copyStyle
  14. } = require('../utils/copy-style');
  15. // Worksheet requirements
  16. // Operate as sheet inside workbook or standalone
  17. // Load and Save from file and stream
  18. // Access/Add/Delete individual cells
  19. // Manage column widths and row heights
  20. class Worksheet {
  21. constructor(options) {
  22. options = options || {};
  23. this._workbook = options.workbook;
  24. // in a workbook, each sheet will have a number
  25. this.id = options.id;
  26. this.orderNo = options.orderNo;
  27. // and a name
  28. this.name = options.name;
  29. // add a state
  30. this.state = options.state || 'visible';
  31. // rows allows access organised by row. Sparse array of arrays indexed by row-1, col
  32. // Note: _rows is zero based. Must subtract 1 to go from cell.row to index
  33. this._rows = [];
  34. // column definitions
  35. this._columns = null;
  36. // column keys (addRow convenience): key ==> this._collumns index
  37. this._keys = {};
  38. // keep record of all merges
  39. this._merges = {};
  40. // record of all row and column pageBreaks
  41. this.rowBreaks = [];
  42. // for tabColor, default row height, outline levels, etc
  43. this.properties = Object.assign({}, {
  44. defaultRowHeight: 15,
  45. dyDescent: 55,
  46. outlineLevelCol: 0,
  47. outlineLevelRow: 0
  48. }, options.properties);
  49. // for all things printing
  50. this.pageSetup = Object.assign({}, {
  51. margins: {
  52. left: 0.7,
  53. right: 0.7,
  54. top: 0.75,
  55. bottom: 0.75,
  56. header: 0.3,
  57. footer: 0.3
  58. },
  59. orientation: 'portrait',
  60. horizontalDpi: 4294967295,
  61. verticalDpi: 4294967295,
  62. fitToPage: !!(options.pageSetup && (options.pageSetup.fitToWidth || options.pageSetup.fitToHeight) && !options.pageSetup.scale),
  63. pageOrder: 'downThenOver',
  64. blackAndWhite: false,
  65. draft: false,
  66. cellComments: 'None',
  67. errors: 'displayed',
  68. scale: 100,
  69. fitToWidth: 1,
  70. fitToHeight: 1,
  71. paperSize: undefined,
  72. showRowColHeaders: false,
  73. showGridLines: false,
  74. firstPageNumber: undefined,
  75. horizontalCentered: false,
  76. verticalCentered: false,
  77. rowBreaks: null,
  78. colBreaks: null
  79. }, options.pageSetup);
  80. this.headerFooter = Object.assign({}, {
  81. differentFirst: false,
  82. differentOddEven: false,
  83. oddHeader: null,
  84. oddFooter: null,
  85. evenHeader: null,
  86. evenFooter: null,
  87. firstHeader: null,
  88. firstFooter: null
  89. }, options.headerFooter);
  90. this.dataValidations = new DataValidations();
  91. // for freezepanes, split, zoom, gridlines, etc
  92. this.views = options.views || [];
  93. this.autoFilter = options.autoFilter || null;
  94. // for images, etc
  95. this._media = [];
  96. // worksheet protection
  97. this.sheetProtection = null;
  98. // for tables
  99. this.tables = {};
  100. this.conditionalFormattings = [];
  101. }
  102. get name() {
  103. return this._name;
  104. }
  105. set name(name) {
  106. if (name === undefined) {
  107. name = `sheet${this.id}`;
  108. }
  109. if (this._name === name) return;
  110. if (typeof name !== 'string') {
  111. throw new Error('The name has to be a string.');
  112. }
  113. if (name === '') {
  114. throw new Error('The name can\'t be empty.');
  115. }
  116. if (name === 'History') {
  117. throw new Error('The name "History" is protected. Please use a different name.');
  118. }
  119. // Illegal character in worksheet name: asterisk (*), question mark (?),
  120. // colon (:), forward slash (/ \), or bracket ([])
  121. if (/[*?:/\\[\]]/.test(name)) {
  122. throw new Error(`Worksheet name ${name} cannot include any of the following characters: * ? : \\ / [ ]`);
  123. }
  124. if (/(^')|('$)/.test(name)) {
  125. throw new Error(`The first or last character of worksheet name cannot be a single quotation mark: ${name}`);
  126. }
  127. if (name && name.length > 31) {
  128. // eslint-disable-next-line no-console
  129. console.warn(`Worksheet name ${name} exceeds 31 chars. This will be truncated`);
  130. name = name.substring(0, 31);
  131. }
  132. if (this._workbook._worksheets.find(ws => ws && ws.name.toLowerCase() === name.toLowerCase())) {
  133. throw new Error(`Worksheet name already exists: ${name}`);
  134. }
  135. this._name = name;
  136. }
  137. get workbook() {
  138. return this._workbook;
  139. }
  140. // when you're done with this worksheet, call this to remove from workbook
  141. destroy() {
  142. this._workbook.removeWorksheetEx(this);
  143. }
  144. // Get the bounding range of the cells in this worksheet
  145. get dimensions() {
  146. const dimensions = new Range();
  147. this._rows.forEach(row => {
  148. if (row) {
  149. const rowDims = row.dimensions;
  150. if (rowDims) {
  151. dimensions.expand(row.number, rowDims.min, row.number, rowDims.max);
  152. }
  153. }
  154. });
  155. return dimensions;
  156. }
  157. // =========================================================================
  158. // Columns
  159. // get the current columns array.
  160. get columns() {
  161. return this._columns;
  162. }
  163. // set the columns from an array of column definitions.
  164. // Note: any headers defined will overwrite existing values.
  165. set columns(value) {
  166. // calculate max header row count
  167. this._headerRowCount = value.reduce((pv, cv) => {
  168. const headerCount = cv.header && 1 || cv.headers && cv.headers.length || 0;
  169. return Math.max(pv, headerCount);
  170. }, 0);
  171. // construct Column objects
  172. let count = 1;
  173. const columns = this._columns = [];
  174. value.forEach(defn => {
  175. const column = new Column(this, count++, false);
  176. columns.push(column);
  177. column.defn = defn;
  178. });
  179. }
  180. getColumnKey(key) {
  181. return this._keys[key];
  182. }
  183. setColumnKey(key, value) {
  184. this._keys[key] = value;
  185. }
  186. deleteColumnKey(key) {
  187. delete this._keys[key];
  188. }
  189. eachColumnKey(f) {
  190. _.each(this._keys, f);
  191. }
  192. // get a single column by col number. If it doesn't exist, create it and any gaps before it
  193. getColumn(c) {
  194. if (typeof c === 'string') {
  195. // if it matches a key'd column, return that
  196. const col = this._keys[c];
  197. if (col) return col;
  198. // otherwise, assume letter
  199. c = colCache.l2n(c);
  200. }
  201. if (!this._columns) {
  202. this._columns = [];
  203. }
  204. if (c > this._columns.length) {
  205. let n = this._columns.length + 1;
  206. while (n <= c) {
  207. this._columns.push(new Column(this, n++));
  208. }
  209. }
  210. return this._columns[c - 1];
  211. }
  212. spliceColumns(start, count) {
  213. const rows = this._rows;
  214. const nRows = rows.length;
  215. for (var _len = arguments.length, inserts = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
  216. inserts[_key - 2] = arguments[_key];
  217. }
  218. if (inserts.length > 0) {
  219. // must iterate over all rows whether they exist yet or not
  220. for (let i = 0; i < nRows; i++) {
  221. const rowArguments = [start, count];
  222. // eslint-disable-next-line no-loop-func
  223. inserts.forEach(insert => {
  224. rowArguments.push(insert[i] || null);
  225. });
  226. const row = this.getRow(i + 1);
  227. // eslint-disable-next-line prefer-spread
  228. row.splice.apply(row, rowArguments);
  229. }
  230. } else {
  231. // nothing to insert, so just splice all rows
  232. this._rows.forEach(r => {
  233. if (r) {
  234. r.splice(start, count);
  235. }
  236. });
  237. }
  238. // splice column definitions
  239. const nExpand = inserts.length - count;
  240. const nKeep = start + count;
  241. const nEnd = this._columns.length;
  242. if (nExpand < 0) {
  243. for (let i = start + inserts.length; i <= nEnd; i++) {
  244. this.getColumn(i).defn = this.getColumn(i - nExpand).defn;
  245. }
  246. } else if (nExpand > 0) {
  247. for (let i = nEnd; i >= nKeep; i--) {
  248. this.getColumn(i + nExpand).defn = this.getColumn(i).defn;
  249. }
  250. }
  251. for (let i = start; i < start + inserts.length; i++) {
  252. this.getColumn(i).defn = null;
  253. }
  254. // account for defined names
  255. this.workbook.definedNames.spliceColumns(this.name, start, count, inserts.length);
  256. }
  257. get lastColumn() {
  258. return this.getColumn(this.columnCount);
  259. }
  260. get columnCount() {
  261. let maxCount = 0;
  262. this.eachRow(row => {
  263. maxCount = Math.max(maxCount, row.cellCount);
  264. });
  265. return maxCount;
  266. }
  267. get actualColumnCount() {
  268. // performance nightmare - for each row, counts all the columns used
  269. const counts = [];
  270. let count = 0;
  271. this.eachRow(row => {
  272. row.eachCell(_ref => {
  273. let {
  274. col
  275. } = _ref;
  276. if (!counts[col]) {
  277. counts[col] = true;
  278. count++;
  279. }
  280. });
  281. });
  282. return count;
  283. }
  284. // =========================================================================
  285. // Rows
  286. _commitRow() {
  287. // nop - allows streaming reader to fill a document
  288. }
  289. get _lastRowNumber() {
  290. // need to cope with results of splice
  291. const rows = this._rows;
  292. let n = rows.length;
  293. while (n > 0 && rows[n - 1] === undefined) {
  294. n--;
  295. }
  296. return n;
  297. }
  298. get _nextRow() {
  299. return this._lastRowNumber + 1;
  300. }
  301. get lastRow() {
  302. if (this._rows.length) {
  303. return this._rows[this._rows.length - 1];
  304. }
  305. return undefined;
  306. }
  307. // find a row (if exists) by row number
  308. findRow(r) {
  309. return this._rows[r - 1];
  310. }
  311. // find multiple rows (if exists) by row number
  312. findRows(start, length) {
  313. return this._rows.slice(start - 1, start - 1 + length);
  314. }
  315. get rowCount() {
  316. return this._lastRowNumber;
  317. }
  318. get actualRowCount() {
  319. // counts actual rows that have actual data
  320. let count = 0;
  321. this.eachRow(() => {
  322. count++;
  323. });
  324. return count;
  325. }
  326. // get a row by row number.
  327. getRow(r) {
  328. let row = this._rows[r - 1];
  329. if (!row) {
  330. row = this._rows[r - 1] = new Row(this, r);
  331. }
  332. return row;
  333. }
  334. // get multiple rows by row number.
  335. getRows(start, length) {
  336. if (length < 1) return undefined;
  337. const rows = [];
  338. for (let i = start; i < start + length; i++) {
  339. rows.push(this.getRow(i));
  340. }
  341. return rows;
  342. }
  343. addRow(value) {
  344. let style = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'n';
  345. const rowNo = this._nextRow;
  346. const row = this.getRow(rowNo);
  347. row.values = value;
  348. this._setStyleOption(rowNo, style[0] === 'i' ? style : 'n');
  349. return row;
  350. }
  351. addRows(value) {
  352. let style = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'n';
  353. const rows = [];
  354. value.forEach(row => {
  355. rows.push(this.addRow(row, style));
  356. });
  357. return rows;
  358. }
  359. insertRow(pos, value) {
  360. let style = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'n';
  361. this.spliceRows(pos, 0, value);
  362. this._setStyleOption(pos, style);
  363. return this.getRow(pos);
  364. }
  365. insertRows(pos, values) {
  366. let style = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'n';
  367. this.spliceRows(pos, 0, ...values);
  368. if (style !== 'n') {
  369. // copy over the styles
  370. for (let i = 0; i < values.length; i++) {
  371. if (style[0] === 'o' && this.findRow(values.length + pos + i) !== undefined) {
  372. this._copyStyle(values.length + pos + i, pos + i, style[1] === '+');
  373. } else if (style[0] === 'i' && this.findRow(pos - 1) !== undefined) {
  374. this._copyStyle(pos - 1, pos + i, style[1] === '+');
  375. }
  376. }
  377. }
  378. return this.getRows(pos, values.length);
  379. }
  380. // set row at position to same style as of either pervious row (option 'i') or next row (option 'o')
  381. _setStyleOption(pos) {
  382. let style = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'n';
  383. if (style[0] === 'o' && this.findRow(pos + 1) !== undefined) {
  384. this._copyStyle(pos + 1, pos, style[1] === '+');
  385. } else if (style[0] === 'i' && this.findRow(pos - 1) !== undefined) {
  386. this._copyStyle(pos - 1, pos, style[1] === '+');
  387. }
  388. }
  389. _copyStyle(src, dest) {
  390. let styleEmpty = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
  391. const rSrc = this.getRow(src);
  392. const rDst = this.getRow(dest);
  393. rDst.style = copyStyle(rSrc.style);
  394. // eslint-disable-next-line no-loop-func
  395. rSrc.eachCell({
  396. includeEmpty: styleEmpty
  397. }, (cell, colNumber) => {
  398. rDst.getCell(colNumber).style = copyStyle(cell.style);
  399. });
  400. rDst.height = rSrc.height;
  401. }
  402. duplicateRow(rowNum, count) {
  403. let insert = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
  404. // create count duplicates of rowNum
  405. // either inserting new or overwriting existing rows
  406. const rSrc = this._rows[rowNum - 1];
  407. const inserts = new Array(count).fill(rSrc.values);
  408. this.spliceRows(rowNum + 1, insert ? 0 : count, ...inserts);
  409. // now copy styles...
  410. for (let i = 0; i < count; i++) {
  411. const rDst = this._rows[rowNum + i];
  412. rDst.style = rSrc.style;
  413. rDst.height = rSrc.height;
  414. // eslint-disable-next-line no-loop-func
  415. rSrc.eachCell({
  416. includeEmpty: true
  417. }, (cell, colNumber) => {
  418. rDst.getCell(colNumber).style = cell.style;
  419. });
  420. }
  421. }
  422. spliceRows(start, count) {
  423. // same problem as row.splice, except worse.
  424. const nKeep = start + count;
  425. for (var _len2 = arguments.length, inserts = new Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) {
  426. inserts[_key2 - 2] = arguments[_key2];
  427. }
  428. const nInserts = inserts.length;
  429. const nExpand = nInserts - count;
  430. const nEnd = this._rows.length;
  431. let i;
  432. let rSrc;
  433. if (nExpand < 0) {
  434. // remove rows
  435. if (start === nEnd) {
  436. this._rows[nEnd - 1] = undefined;
  437. }
  438. for (i = nKeep; i <= nEnd; i++) {
  439. rSrc = this._rows[i - 1];
  440. if (rSrc) {
  441. const rDst = this.getRow(i + nExpand);
  442. rDst.values = rSrc.values;
  443. rDst.style = rSrc.style;
  444. rDst.height = rSrc.height;
  445. // eslint-disable-next-line no-loop-func
  446. rSrc.eachCell({
  447. includeEmpty: true
  448. }, (cell, colNumber) => {
  449. rDst.getCell(colNumber).style = cell.style;
  450. });
  451. this._rows[i - 1] = undefined;
  452. } else {
  453. this._rows[i + nExpand - 1] = undefined;
  454. }
  455. }
  456. } else if (nExpand > 0) {
  457. // insert new cells
  458. for (i = nEnd; i >= nKeep; i--) {
  459. rSrc = this._rows[i - 1];
  460. if (rSrc) {
  461. const rDst = this.getRow(i + nExpand);
  462. rDst.values = rSrc.values;
  463. rDst.style = rSrc.style;
  464. rDst.height = rSrc.height;
  465. // eslint-disable-next-line no-loop-func
  466. rSrc.eachCell({
  467. includeEmpty: true
  468. }, (cell, colNumber) => {
  469. rDst.getCell(colNumber).style = cell.style;
  470. // remerge cells accounting for insert offset
  471. if (cell._value.constructor.name === 'MergeValue') {
  472. const cellToBeMerged = this.getRow(cell._row._number + nInserts).getCell(colNumber);
  473. const prevMaster = cell._value._master;
  474. const newMaster = this.getRow(prevMaster._row._number + nInserts).getCell(prevMaster._column._number);
  475. cellToBeMerged.merge(newMaster);
  476. }
  477. });
  478. } else {
  479. this._rows[i + nExpand - 1] = undefined;
  480. }
  481. }
  482. }
  483. // now copy over the new values
  484. for (i = 0; i < nInserts; i++) {
  485. const rDst = this.getRow(start + i);
  486. rDst.style = {};
  487. rDst.values = inserts[i];
  488. }
  489. // account for defined names
  490. this.workbook.definedNames.spliceRows(this.name, start, count, nInserts);
  491. }
  492. // iterate over every row in the worksheet, including maybe empty rows
  493. eachRow(options, iteratee) {
  494. if (!iteratee) {
  495. iteratee = options;
  496. options = undefined;
  497. }
  498. if (options && options.includeEmpty) {
  499. const n = this._rows.length;
  500. for (let i = 1; i <= n; i++) {
  501. iteratee(this.getRow(i), i);
  502. }
  503. } else {
  504. this._rows.forEach(row => {
  505. if (row && row.hasValues) {
  506. iteratee(row, row.number);
  507. }
  508. });
  509. }
  510. }
  511. // return all rows as sparse array
  512. getSheetValues() {
  513. const rows = [];
  514. this._rows.forEach(row => {
  515. if (row) {
  516. rows[row.number] = row.values;
  517. }
  518. });
  519. return rows;
  520. }
  521. // =========================================================================
  522. // Cells
  523. // returns the cell at [r,c] or address given by r. If not found, return undefined
  524. findCell(r, c) {
  525. const address = colCache.getAddress(r, c);
  526. const row = this._rows[address.row - 1];
  527. return row ? row.findCell(address.col) : undefined;
  528. }
  529. // return the cell at [r,c] or address given by r. If not found, create a new one.
  530. getCell(r, c) {
  531. const address = colCache.getAddress(r, c);
  532. const row = this.getRow(address.row);
  533. return row.getCellEx(address);
  534. }
  535. // =========================================================================
  536. // Merge
  537. // convert the range defined by ['tl:br'], [tl,br] or [t,l,b,r] into a single 'merged' cell
  538. mergeCells() {
  539. for (var _len3 = arguments.length, cells = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
  540. cells[_key3] = arguments[_key3];
  541. }
  542. const dimensions = new Range(cells);
  543. this._mergeCellsInternal(dimensions);
  544. }
  545. mergeCellsWithoutStyle() {
  546. for (var _len4 = arguments.length, cells = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
  547. cells[_key4] = arguments[_key4];
  548. }
  549. const dimensions = new Range(cells);
  550. this._mergeCellsInternal(dimensions, true);
  551. }
  552. _mergeCellsInternal(dimensions, ignoreStyle) {
  553. // check cells aren't already merged
  554. _.each(this._merges, merge => {
  555. if (merge.intersects(dimensions)) {
  556. throw new Error('Cannot merge already merged cells');
  557. }
  558. });
  559. // apply merge
  560. const master = this.getCell(dimensions.top, dimensions.left);
  561. for (let i = dimensions.top; i <= dimensions.bottom; i++) {
  562. for (let j = dimensions.left; j <= dimensions.right; j++) {
  563. // merge all but the master cell
  564. if (i > dimensions.top || j > dimensions.left) {
  565. this.getCell(i, j).merge(master, ignoreStyle);
  566. }
  567. }
  568. }
  569. // index merge
  570. this._merges[master.address] = dimensions;
  571. }
  572. _unMergeMaster(master) {
  573. // master is always top left of a rectangle
  574. const merge = this._merges[master.address];
  575. if (merge) {
  576. for (let i = merge.top; i <= merge.bottom; i++) {
  577. for (let j = merge.left; j <= merge.right; j++) {
  578. this.getCell(i, j).unmerge();
  579. }
  580. }
  581. delete this._merges[master.address];
  582. }
  583. }
  584. get hasMerges() {
  585. // return true if this._merges has a merge object
  586. return _.some(this._merges, Boolean);
  587. }
  588. // scan the range defined by ['tl:br'], [tl,br] or [t,l,b,r] and if any cell is part of a merge,
  589. // un-merge the group. Note this function can affect multiple merges and merge-blocks are
  590. // atomic - either they're all merged or all un-merged.
  591. unMergeCells() {
  592. for (var _len5 = arguments.length, cells = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {
  593. cells[_key5] = arguments[_key5];
  594. }
  595. const dimensions = new Range(cells);
  596. // find any cells in that range and unmerge them
  597. for (let i = dimensions.top; i <= dimensions.bottom; i++) {
  598. for (let j = dimensions.left; j <= dimensions.right; j++) {
  599. const cell = this.findCell(i, j);
  600. if (cell) {
  601. if (cell.type === Enums.ValueType.Merge) {
  602. // this cell merges to another master
  603. this._unMergeMaster(cell.master);
  604. } else if (this._merges[cell.address]) {
  605. // this cell is a master
  606. this._unMergeMaster(cell);
  607. }
  608. }
  609. }
  610. }
  611. }
  612. // ===========================================================================
  613. // Shared/Array Formula
  614. fillFormula(range, formula, results) {
  615. let shareType = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 'shared';
  616. // Define formula for top-left cell and share to rest
  617. const decoded = colCache.decode(range);
  618. const {
  619. top,
  620. left,
  621. bottom,
  622. right
  623. } = decoded;
  624. const width = right - left + 1;
  625. const masterAddress = colCache.encodeAddress(top, left);
  626. const isShared = shareType === 'shared';
  627. // work out result accessor
  628. let getResult;
  629. if (typeof results === 'function') {
  630. getResult = results;
  631. } else if (Array.isArray(results)) {
  632. if (Array.isArray(results[0])) {
  633. getResult = (row, col) => results[row - top][col - left];
  634. } else {
  635. // eslint-disable-next-line no-mixed-operators
  636. getResult = (row, col) => results[(row - top) * width + (col - left)];
  637. }
  638. } else {
  639. getResult = () => undefined;
  640. }
  641. let first = true;
  642. for (let r = top; r <= bottom; r++) {
  643. for (let c = left; c <= right; c++) {
  644. if (first) {
  645. this.getCell(r, c).value = {
  646. shareType,
  647. formula,
  648. ref: range,
  649. result: getResult(r, c)
  650. };
  651. first = false;
  652. } else {
  653. this.getCell(r, c).value = isShared ? {
  654. sharedFormula: masterAddress,
  655. result: getResult(r, c)
  656. } : getResult(r, c);
  657. }
  658. }
  659. }
  660. }
  661. // =========================================================================
  662. // Images
  663. addImage(imageId, range) {
  664. const model = {
  665. type: 'image',
  666. imageId,
  667. range
  668. };
  669. this._media.push(new Image(this, model));
  670. }
  671. getImages() {
  672. return this._media.filter(m => m.type === 'image');
  673. }
  674. addBackgroundImage(imageId) {
  675. const model = {
  676. type: 'background',
  677. imageId
  678. };
  679. this._media.push(new Image(this, model));
  680. }
  681. getBackgroundImageId() {
  682. const image = this._media.find(m => m.type === 'background');
  683. return image && image.imageId;
  684. }
  685. // =========================================================================
  686. // Worksheet Protection
  687. protect(password, options) {
  688. // TODO: make this function truly async
  689. // perhaps marshal to worker thread or something
  690. return new Promise(resolve => {
  691. this.sheetProtection = {
  692. sheet: true
  693. };
  694. if (options && 'spinCount' in options) {
  695. // force spinCount to be integer >= 0
  696. options.spinCount = Number.isFinite(options.spinCount) ? Math.round(Math.max(0, options.spinCount)) : 100000;
  697. }
  698. if (password) {
  699. this.sheetProtection.algorithmName = 'SHA-512';
  700. this.sheetProtection.saltValue = Encryptor.randomBytes(16).toString('base64');
  701. this.sheetProtection.spinCount = options && 'spinCount' in options ? options.spinCount : 100000; // allow user specified spinCount
  702. this.sheetProtection.hashValue = Encryptor.convertPasswordToHash(password, 'SHA512', this.sheetProtection.saltValue, this.sheetProtection.spinCount);
  703. }
  704. if (options) {
  705. this.sheetProtection = Object.assign(this.sheetProtection, options);
  706. if (!password && 'spinCount' in options) {
  707. delete this.sheetProtection.spinCount;
  708. }
  709. }
  710. resolve();
  711. });
  712. }
  713. unprotect() {
  714. this.sheetProtection = null;
  715. }
  716. // =========================================================================
  717. // Tables
  718. addTable(model) {
  719. const table = new Table(this, model);
  720. this.tables[model.name] = table;
  721. return table;
  722. }
  723. getTable(name) {
  724. return this.tables[name];
  725. }
  726. removeTable(name) {
  727. delete this.tables[name];
  728. }
  729. getTables() {
  730. return Object.values(this.tables);
  731. }
  732. // ===========================================================================
  733. // Conditional Formatting
  734. addConditionalFormatting(cf) {
  735. this.conditionalFormattings.push(cf);
  736. }
  737. removeConditionalFormatting(filter) {
  738. if (typeof filter === 'number') {
  739. this.conditionalFormattings.splice(filter, 1);
  740. } else if (filter instanceof Function) {
  741. this.conditionalFormattings = this.conditionalFormattings.filter(filter);
  742. } else {
  743. this.conditionalFormattings = [];
  744. }
  745. }
  746. // ===========================================================================
  747. // Deprecated
  748. get tabColor() {
  749. // eslint-disable-next-line no-console
  750. console.trace('worksheet.tabColor property is now deprecated. Please use worksheet.properties.tabColor');
  751. return this.properties.tabColor;
  752. }
  753. set tabColor(value) {
  754. // eslint-disable-next-line no-console
  755. console.trace('worksheet.tabColor property is now deprecated. Please use worksheet.properties.tabColor');
  756. this.properties.tabColor = value;
  757. }
  758. // ===========================================================================
  759. // Model
  760. get model() {
  761. const model = {
  762. id: this.id,
  763. name: this.name,
  764. dataValidations: this.dataValidations.model,
  765. properties: this.properties,
  766. state: this.state,
  767. pageSetup: this.pageSetup,
  768. headerFooter: this.headerFooter,
  769. rowBreaks: this.rowBreaks,
  770. views: this.views,
  771. autoFilter: this.autoFilter,
  772. media: this._media.map(medium => medium.model),
  773. sheetProtection: this.sheetProtection,
  774. tables: Object.values(this.tables).map(table => table.model),
  775. conditionalFormattings: this.conditionalFormattings
  776. };
  777. // =================================================
  778. // columns
  779. model.cols = Column.toModel(this.columns);
  780. // ==========================================================
  781. // Rows
  782. const rows = model.rows = [];
  783. const dimensions = model.dimensions = new Range();
  784. this._rows.forEach(row => {
  785. const rowModel = row && row.model;
  786. if (rowModel) {
  787. dimensions.expand(rowModel.number, rowModel.min, rowModel.number, rowModel.max);
  788. rows.push(rowModel);
  789. }
  790. });
  791. // ==========================================================
  792. // Merges
  793. model.merges = [];
  794. _.each(this._merges, merge => {
  795. model.merges.push(merge.range);
  796. });
  797. return model;
  798. }
  799. _parseRows(model) {
  800. this._rows = [];
  801. model.rows.forEach(rowModel => {
  802. const row = new Row(this, rowModel.number);
  803. this._rows[row.number - 1] = row;
  804. row.model = rowModel;
  805. });
  806. }
  807. _parseMergeCells(model) {
  808. _.each(model.mergeCells, merge => {
  809. // Do not merge styles when importing an Excel file
  810. // since each cell may have different styles intentionally.
  811. this.mergeCellsWithoutStyle(merge);
  812. });
  813. }
  814. set model(value) {
  815. this.name = value.name;
  816. this._columns = Column.fromModel(this, value.cols);
  817. this._parseRows(value);
  818. this._parseMergeCells(value);
  819. this.dataValidations = new DataValidations(value.dataValidations);
  820. this.properties = value.properties;
  821. this.pageSetup = value.pageSetup;
  822. this.headerFooter = value.headerFooter;
  823. this.views = value.views;
  824. this.autoFilter = value.autoFilter;
  825. this._media = value.media.map(medium => new Image(this, medium));
  826. this.sheetProtection = value.sheetProtection;
  827. this.tables = value.tables.reduce((tables, table) => {
  828. const t = new Table();
  829. t.model = table;
  830. tables[table.name] = t;
  831. return tables;
  832. }, {});
  833. this.conditionalFormattings = value.conditionalFormattings;
  834. }
  835. }
  836. module.exports = Worksheet;
  837. //# sourceMappingURL=worksheet.js.map