worksheet.js 26 KB

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