worksheet-writer.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652
  1. "use strict";
  2. const _ = require('../../utils/under-dash');
  3. const RelType = require('../../xlsx/rel-type');
  4. const colCache = require('../../utils/col-cache');
  5. const Encryptor = require('../../utils/encryptor');
  6. const Dimensions = require('../../doc/range');
  7. const StringBuf = require('../../utils/string-buf');
  8. const Row = require('../../doc/row');
  9. const Column = require('../../doc/column');
  10. const SheetRelsWriter = require('./sheet-rels-writer');
  11. const SheetCommentsWriter = require('./sheet-comments-writer');
  12. const DataValidations = require('../../doc/data-validations');
  13. const xmlBuffer = new StringBuf();
  14. // ============================================================================================
  15. // Xforms
  16. const ListXform = require('../../xlsx/xform/list-xform');
  17. const DataValidationsXform = require('../../xlsx/xform/sheet/data-validations-xform');
  18. const SheetPropertiesXform = require('../../xlsx/xform/sheet/sheet-properties-xform');
  19. const SheetFormatPropertiesXform = require('../../xlsx/xform/sheet/sheet-format-properties-xform');
  20. const ColXform = require('../../xlsx/xform/sheet/col-xform');
  21. const RowXform = require('../../xlsx/xform/sheet/row-xform');
  22. const HyperlinkXform = require('../../xlsx/xform/sheet/hyperlink-xform');
  23. const SheetViewXform = require('../../xlsx/xform/sheet/sheet-view-xform');
  24. const SheetProtectionXform = require('../../xlsx/xform/sheet/sheet-protection-xform');
  25. const PageMarginsXform = require('../../xlsx/xform/sheet/page-margins-xform');
  26. const PageSetupXform = require('../../xlsx/xform/sheet/page-setup-xform');
  27. const AutoFilterXform = require('../../xlsx/xform/sheet/auto-filter-xform');
  28. const PictureXform = require('../../xlsx/xform/sheet/picture-xform');
  29. const ConditionalFormattingsXform = require('../../xlsx/xform/sheet/cf/conditional-formattings-xform');
  30. const HeaderFooterXform = require('../../xlsx/xform/sheet/header-footer-xform');
  31. const RowBreaksXform = require('../../xlsx/xform/sheet/row-breaks-xform');
  32. // since prepare and render are functional, we can use singletons
  33. const xform = {
  34. dataValidations: new DataValidationsXform(),
  35. sheetProperties: new SheetPropertiesXform(),
  36. sheetFormatProperties: new SheetFormatPropertiesXform(),
  37. columns: new ListXform({
  38. tag: 'cols',
  39. length: false,
  40. childXform: new ColXform()
  41. }),
  42. row: new RowXform(),
  43. hyperlinks: new ListXform({
  44. tag: 'hyperlinks',
  45. length: false,
  46. childXform: new HyperlinkXform()
  47. }),
  48. sheetViews: new ListXform({
  49. tag: 'sheetViews',
  50. length: false,
  51. childXform: new SheetViewXform()
  52. }),
  53. sheetProtection: new SheetProtectionXform(),
  54. pageMargins: new PageMarginsXform(),
  55. pageSeteup: new PageSetupXform(),
  56. autoFilter: new AutoFilterXform(),
  57. picture: new PictureXform(),
  58. conditionalFormattings: new ConditionalFormattingsXform(),
  59. headerFooter: new HeaderFooterXform(),
  60. rowBreaks: new RowBreaksXform()
  61. };
  62. // ============================================================================================
  63. class WorksheetWriter {
  64. constructor(options) {
  65. // in a workbook, each sheet will have a number
  66. this.id = options.id;
  67. // and a name
  68. this.name = options.name || `Sheet${this.id}`;
  69. // add a state
  70. this.state = options.state || 'visible';
  71. // rows are stored here while they need to be worked on.
  72. // when they are committed, they will be deleted.
  73. this._rows = [];
  74. // column definitions
  75. this._columns = null;
  76. // column keys (addRow convenience): key ==> this._columns index
  77. this._keys = {};
  78. // keep a record of all row and column pageBreaks
  79. this._merges = [];
  80. this._merges.add = function () {}; // ignore cell instruction
  81. // keep record of all hyperlinks
  82. this._sheetRelsWriter = new SheetRelsWriter(options);
  83. this._sheetCommentsWriter = new SheetCommentsWriter(this, this._sheetRelsWriter, options);
  84. // keep a record of dimensions
  85. this._dimensions = new Dimensions();
  86. // first uncommitted row
  87. this._rowZero = 1;
  88. // committed flag
  89. this.committed = false;
  90. // for data validations
  91. this.dataValidations = new DataValidations();
  92. // for sharing formulae
  93. this._formulae = {};
  94. this._siFormulae = 0;
  95. // keep a record of conditionalFormattings
  96. this.conditionalFormatting = [];
  97. // keep a record of all row and column pageBreaks
  98. this.rowBreaks = [];
  99. // for default row height, outline levels, etc
  100. this.properties = Object.assign({}, {
  101. defaultRowHeight: 15,
  102. dyDescent: 55,
  103. outlineLevelCol: 0,
  104. outlineLevelRow: 0
  105. }, options.properties);
  106. this.headerFooter = Object.assign({}, {
  107. differentFirst: false,
  108. differentOddEven: false,
  109. oddHeader: null,
  110. oddFooter: null,
  111. evenHeader: null,
  112. evenFooter: null,
  113. firstHeader: null,
  114. firstFooter: null
  115. }, options.headerFooter);
  116. // for all things printing
  117. this.pageSetup = Object.assign({}, {
  118. margins: {
  119. left: 0.7,
  120. right: 0.7,
  121. top: 0.75,
  122. bottom: 0.75,
  123. header: 0.3,
  124. footer: 0.3
  125. },
  126. orientation: 'portrait',
  127. horizontalDpi: 4294967295,
  128. verticalDpi: 4294967295,
  129. fitToPage: !!(options.pageSetup && (options.pageSetup.fitToWidth || options.pageSetup.fitToHeight) && !options.pageSetup.scale),
  130. pageOrder: 'downThenOver',
  131. blackAndWhite: false,
  132. draft: false,
  133. cellComments: 'None',
  134. errors: 'displayed',
  135. scale: 100,
  136. fitToWidth: 1,
  137. fitToHeight: 1,
  138. paperSize: undefined,
  139. showRowColHeaders: false,
  140. showGridLines: false,
  141. horizontalCentered: false,
  142. verticalCentered: false,
  143. rowBreaks: null,
  144. colBreaks: null
  145. }, options.pageSetup);
  146. // using shared strings creates a smaller xlsx file but may use more memory
  147. this.useSharedStrings = options.useSharedStrings || false;
  148. this._workbook = options.workbook;
  149. this.hasComments = false;
  150. // views
  151. this._views = options.views || [];
  152. // auto filter
  153. this.autoFilter = options.autoFilter || null;
  154. this._media = [];
  155. // worksheet protection
  156. this.sheetProtection = null;
  157. // start writing to stream now
  158. this._writeOpenWorksheet();
  159. this.startedData = false;
  160. }
  161. get workbook() {
  162. return this._workbook;
  163. }
  164. get stream() {
  165. if (!this._stream) {
  166. // eslint-disable-next-line no-underscore-dangle
  167. this._stream = this._workbook._openStream(`/xl/worksheets/sheet${this.id}.xml`);
  168. // pause stream to prevent 'data' events
  169. this._stream.pause();
  170. }
  171. return this._stream;
  172. }
  173. // destroy - not a valid operation for a streaming writer
  174. // even though some streamers might be able to, it's a bad idea.
  175. destroy() {
  176. throw new Error('Invalid Operation: destroy');
  177. }
  178. commit() {
  179. if (this.committed) {
  180. return;
  181. }
  182. // commit all rows
  183. this._rows.forEach(cRow => {
  184. if (cRow) {
  185. // write the row to the stream
  186. this._writeRow(cRow);
  187. }
  188. });
  189. // we _cannot_ accept new rows from now on
  190. this._rows = null;
  191. if (!this.startedData) {
  192. this._writeOpenSheetData();
  193. }
  194. this._writeCloseSheetData();
  195. this._writeAutoFilter();
  196. this._writeMergeCells();
  197. // for some reason, Excel can't handle dimensions at the bottom of the file
  198. // this._writeDimensions();
  199. this._writeHyperlinks();
  200. this._writeConditionalFormatting();
  201. this._writeDataValidations();
  202. this._writeSheetProtection();
  203. this._writePageMargins();
  204. this._writePageSetup();
  205. this._writeBackground();
  206. this._writeHeaderFooter();
  207. this._writeRowBreaks();
  208. // Legacy Data tag for comments
  209. this._writeLegacyData();
  210. this._writeCloseWorksheet();
  211. // signal end of stream to workbook
  212. this.stream.end();
  213. this._sheetCommentsWriter.commit();
  214. // also commit the hyperlinks if any
  215. this._sheetRelsWriter.commit();
  216. this.committed = true;
  217. }
  218. // return the current dimensions of the writer
  219. get dimensions() {
  220. return this._dimensions;
  221. }
  222. get views() {
  223. return this._views;
  224. }
  225. // =========================================================================
  226. // Columns
  227. // get the current columns array.
  228. get columns() {
  229. return this._columns;
  230. }
  231. // set the columns from an array of column definitions.
  232. // Note: any headers defined will overwrite existing values.
  233. set columns(value) {
  234. // calculate max header row count
  235. this._headerRowCount = value.reduce((pv, cv) => {
  236. const headerCount = cv.header && 1 || cv.headers && cv.headers.length || 0;
  237. return Math.max(pv, headerCount);
  238. }, 0);
  239. // construct Column objects
  240. let count = 1;
  241. const columns = this._columns = [];
  242. value.forEach(defn => {
  243. const column = new Column(this, count++, false);
  244. columns.push(column);
  245. column.defn = defn;
  246. });
  247. }
  248. getColumnKey(key) {
  249. return this._keys[key];
  250. }
  251. setColumnKey(key, value) {
  252. this._keys[key] = value;
  253. }
  254. deleteColumnKey(key) {
  255. delete this._keys[key];
  256. }
  257. eachColumnKey(f) {
  258. _.each(this._keys, f);
  259. }
  260. // get a single column by col number. If it doesn't exist, it and any gaps before it
  261. // are created.
  262. getColumn(c) {
  263. if (typeof c === 'string') {
  264. // if it matches a key'd column, return that
  265. const col = this._keys[c];
  266. if (col) return col;
  267. // otherwise, assume letter
  268. c = colCache.l2n(c);
  269. }
  270. if (!this._columns) {
  271. this._columns = [];
  272. }
  273. if (c > this._columns.length) {
  274. let n = this._columns.length + 1;
  275. while (n <= c) {
  276. this._columns.push(new Column(this, n++));
  277. }
  278. }
  279. return this._columns[c - 1];
  280. }
  281. // =========================================================================
  282. // Rows
  283. get _nextRow() {
  284. return this._rowZero + this._rows.length;
  285. }
  286. // iterate over every uncommitted row in the worksheet, including maybe empty rows
  287. eachRow(options, iteratee) {
  288. if (!iteratee) {
  289. iteratee = options;
  290. options = undefined;
  291. }
  292. if (options && options.includeEmpty) {
  293. const n = this._nextRow;
  294. for (let i = this._rowZero; i < n; i++) {
  295. iteratee(this.getRow(i), i);
  296. }
  297. } else {
  298. this._rows.forEach(row => {
  299. if (row.hasValues) {
  300. iteratee(row, row.number);
  301. }
  302. });
  303. }
  304. }
  305. _commitRow(cRow) {
  306. // since rows must be written in order, we commit all rows up till and including cRow
  307. let found = false;
  308. while (this._rows.length && !found) {
  309. const row = this._rows.shift();
  310. this._rowZero++;
  311. if (row) {
  312. this._writeRow(row);
  313. found = row.number === cRow.number;
  314. this._rowZero = row.number + 1;
  315. }
  316. }
  317. }
  318. get lastRow() {
  319. // returns last uncommitted row
  320. if (this._rows.length) {
  321. return this._rows[this._rows.length - 1];
  322. }
  323. return undefined;
  324. }
  325. // find a row (if exists) by row number
  326. findRow(rowNumber) {
  327. const index = rowNumber - this._rowZero;
  328. return this._rows[index];
  329. }
  330. getRow(rowNumber) {
  331. const index = rowNumber - this._rowZero;
  332. // may fail if rows have been comitted
  333. if (index < 0) {
  334. throw new Error('Out of bounds: this row has been committed');
  335. }
  336. let row = this._rows[index];
  337. if (!row) {
  338. this._rows[index] = row = new Row(this, rowNumber);
  339. }
  340. return row;
  341. }
  342. addRow(value) {
  343. const row = new Row(this, this._nextRow);
  344. this._rows[row.number - this._rowZero] = row;
  345. row.values = value;
  346. return row;
  347. }
  348. // ================================================================================
  349. // Cells
  350. // returns the cell at [r,c] or address given by r. If not found, return undefined
  351. findCell(r, c) {
  352. const address = colCache.getAddress(r, c);
  353. const row = this.findRow(address.row);
  354. return row ? row.findCell(address.column) : undefined;
  355. }
  356. // return the cell at [r,c] or address given by r. If not found, create a new one.
  357. getCell(r, c) {
  358. const address = colCache.getAddress(r, c);
  359. const row = this.getRow(address.row);
  360. return row.getCellEx(address);
  361. }
  362. mergeCells() {
  363. for (var _len = arguments.length, cells = new Array(_len), _key = 0; _key < _len; _key++) {
  364. cells[_key] = arguments[_key];
  365. }
  366. // may fail if rows have been comitted
  367. const dimensions = new Dimensions(cells);
  368. // check cells aren't already merged
  369. this._merges.forEach(merge => {
  370. if (merge.intersects(dimensions)) {
  371. throw new Error('Cannot merge already merged cells');
  372. }
  373. });
  374. // apply merge
  375. const master = this.getCell(dimensions.top, dimensions.left);
  376. for (let i = dimensions.top; i <= dimensions.bottom; i++) {
  377. for (let j = dimensions.left; j <= dimensions.right; j++) {
  378. if (i > dimensions.top || j > dimensions.left) {
  379. this.getCell(i, j).merge(master);
  380. }
  381. }
  382. }
  383. // index merge
  384. this._merges.push(dimensions);
  385. }
  386. // ===========================================================================
  387. // Conditional Formatting
  388. addConditionalFormatting(cf) {
  389. this.conditionalFormatting.push(cf);
  390. }
  391. removeConditionalFormatting(filter) {
  392. if (typeof filter === 'number') {
  393. this.conditionalFormatting.splice(filter, 1);
  394. } else if (filter instanceof Function) {
  395. this.conditionalFormatting = this.conditionalFormatting.filter(filter);
  396. } else {
  397. this.conditionalFormatting = [];
  398. }
  399. }
  400. // =========================================================================
  401. addBackgroundImage(imageId) {
  402. this._background = {
  403. imageId
  404. };
  405. }
  406. getBackgroundImageId() {
  407. return this._background && this._background.imageId;
  408. }
  409. // =========================================================================
  410. // Worksheet Protection
  411. protect(password, options) {
  412. // TODO: make this function truly async
  413. // perhaps marshal to worker thread or something
  414. return new Promise(resolve => {
  415. this.sheetProtection = {
  416. sheet: true
  417. };
  418. if (options && 'spinCount' in options) {
  419. // force spinCount to be integer >= 0
  420. options.spinCount = Number.isFinite(options.spinCount) ? Math.round(Math.max(0, options.spinCount)) : 100000;
  421. }
  422. if (password) {
  423. this.sheetProtection.algorithmName = 'SHA-512';
  424. this.sheetProtection.saltValue = Encryptor.randomBytes(16).toString('base64');
  425. this.sheetProtection.spinCount = options && 'spinCount' in options ? options.spinCount : 100000; // allow user specified spinCount
  426. this.sheetProtection.hashValue = Encryptor.convertPasswordToHash(password, 'SHA512', this.sheetProtection.saltValue, this.sheetProtection.spinCount);
  427. }
  428. if (options) {
  429. this.sheetProtection = Object.assign(this.sheetProtection, options);
  430. if (!password && 'spinCount' in options) {
  431. delete this.sheetProtection.spinCount;
  432. }
  433. }
  434. resolve();
  435. });
  436. }
  437. unprotect() {
  438. this.sheetProtection = null;
  439. }
  440. // ================================================================================
  441. _write(text) {
  442. xmlBuffer.reset();
  443. xmlBuffer.addText(text);
  444. this.stream.write(xmlBuffer);
  445. }
  446. _writeSheetProperties(xmlBuf, properties, pageSetup) {
  447. const sheetPropertiesModel = {
  448. outlineProperties: properties && properties.outlineProperties,
  449. tabColor: properties && properties.tabColor,
  450. pageSetup: pageSetup && pageSetup.fitToPage ? {
  451. fitToPage: pageSetup.fitToPage
  452. } : undefined
  453. };
  454. xmlBuf.addText(xform.sheetProperties.toXml(sheetPropertiesModel));
  455. }
  456. _writeSheetFormatProperties(xmlBuf, properties) {
  457. const sheetFormatPropertiesModel = properties ? {
  458. defaultRowHeight: properties.defaultRowHeight,
  459. dyDescent: properties.dyDescent,
  460. outlineLevelCol: properties.outlineLevelCol,
  461. outlineLevelRow: properties.outlineLevelRow
  462. } : undefined;
  463. if (properties.defaultColWidth) {
  464. sheetFormatPropertiesModel.defaultColWidth = properties.defaultColWidth;
  465. }
  466. xmlBuf.addText(xform.sheetFormatProperties.toXml(sheetFormatPropertiesModel));
  467. }
  468. _writeOpenWorksheet() {
  469. xmlBuffer.reset();
  470. xmlBuffer.addText('<?xml version="1.0" encoding="UTF-8" standalone="yes"?>');
  471. xmlBuffer.addText('<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"' + ' xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"' + ' xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"' + ' mc:Ignorable="x14ac"' + ' xmlns:x14ac="http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac">');
  472. this._writeSheetProperties(xmlBuffer, this.properties, this.pageSetup);
  473. xmlBuffer.addText(xform.sheetViews.toXml(this.views));
  474. this._writeSheetFormatProperties(xmlBuffer, this.properties);
  475. this.stream.write(xmlBuffer);
  476. }
  477. _writeColumns() {
  478. const cols = Column.toModel(this.columns);
  479. if (cols) {
  480. xform.columns.prepare(cols, {
  481. styles: this._workbook.styles
  482. });
  483. this.stream.write(xform.columns.toXml(cols));
  484. }
  485. }
  486. _writeOpenSheetData() {
  487. this._write('<sheetData>');
  488. }
  489. _writeRow(row) {
  490. if (!this.startedData) {
  491. this._writeColumns();
  492. this._writeOpenSheetData();
  493. this.startedData = true;
  494. }
  495. if (row.hasValues || row.height) {
  496. const {
  497. model
  498. } = row;
  499. const options = {
  500. styles: this._workbook.styles,
  501. sharedStrings: this.useSharedStrings ? this._workbook.sharedStrings : undefined,
  502. hyperlinks: this._sheetRelsWriter.hyperlinksProxy,
  503. merges: this._merges,
  504. formulae: this._formulae,
  505. siFormulae: this._siFormulae,
  506. comments: []
  507. };
  508. xform.row.prepare(model, options);
  509. this.stream.write(xform.row.toXml(model));
  510. if (options.comments.length) {
  511. this.hasComments = true;
  512. this._sheetCommentsWriter.addComments(options.comments);
  513. }
  514. }
  515. }
  516. _writeCloseSheetData() {
  517. this._write('</sheetData>');
  518. }
  519. _writeMergeCells() {
  520. if (this._merges.length) {
  521. xmlBuffer.reset();
  522. xmlBuffer.addText(`<mergeCells count="${this._merges.length}">`);
  523. this._merges.forEach(merge => {
  524. xmlBuffer.addText(`<mergeCell ref="${merge}"/>`);
  525. });
  526. xmlBuffer.addText('</mergeCells>');
  527. this.stream.write(xmlBuffer);
  528. }
  529. }
  530. _writeHyperlinks() {
  531. // eslint-disable-next-line no-underscore-dangle
  532. this.stream.write(xform.hyperlinks.toXml(this._sheetRelsWriter._hyperlinks));
  533. }
  534. _writeConditionalFormatting() {
  535. const options = {
  536. styles: this._workbook.styles
  537. };
  538. xform.conditionalFormattings.prepare(this.conditionalFormatting, options);
  539. this.stream.write(xform.conditionalFormattings.toXml(this.conditionalFormatting));
  540. }
  541. _writeRowBreaks() {
  542. this.stream.write(xform.rowBreaks.toXml(this.rowBreaks));
  543. }
  544. _writeDataValidations() {
  545. this.stream.write(xform.dataValidations.toXml(this.dataValidations.model));
  546. }
  547. _writeSheetProtection() {
  548. this.stream.write(xform.sheetProtection.toXml(this.sheetProtection));
  549. }
  550. _writePageMargins() {
  551. this.stream.write(xform.pageMargins.toXml(this.pageSetup.margins));
  552. }
  553. _writePageSetup() {
  554. this.stream.write(xform.pageSeteup.toXml(this.pageSetup));
  555. }
  556. _writeHeaderFooter() {
  557. this.stream.write(xform.headerFooter.toXml(this.headerFooter));
  558. }
  559. _writeAutoFilter() {
  560. this.stream.write(xform.autoFilter.toXml(this.autoFilter));
  561. }
  562. _writeBackground() {
  563. if (this._background) {
  564. if (this._background.imageId !== undefined) {
  565. const image = this._workbook.getImage(this._background.imageId);
  566. const pictureId = this._sheetRelsWriter.addMedia({
  567. Target: `../media/${image.name}`,
  568. Type: RelType.Image
  569. });
  570. this._background = {
  571. ...this._background,
  572. rId: pictureId
  573. };
  574. }
  575. this.stream.write(xform.picture.toXml({
  576. rId: this._background.rId
  577. }));
  578. }
  579. }
  580. _writeLegacyData() {
  581. if (this.hasComments) {
  582. xmlBuffer.reset();
  583. xmlBuffer.addText(`<legacyDrawing r:id="${this._sheetCommentsWriter.vmlRelId}"/>`);
  584. this.stream.write(xmlBuffer);
  585. }
  586. }
  587. _writeDimensions() {
  588. // for some reason, Excel can't handle dimensions at the bottom of the file
  589. // and we don't know the dimensions until the commit, so don't write them.
  590. // this._write('<dimension ref="' + this._dimensions + '"/>');
  591. }
  592. _writeCloseWorksheet() {
  593. this._write('</worksheet>');
  594. }
  595. }
  596. module.exports = WorksheetWriter;
  597. //# sourceMappingURL=worksheet-writer.js.map