worksheet.js 24 KB

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