csv.js 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. "use strict";
  2. function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
  3. function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
  4. function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
  5. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  6. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  7. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  8. var fs = require('fs');
  9. var fastCsv = require('fast-csv');
  10. var customParseFormat = require('dayjs/plugin/customParseFormat');
  11. var utc = require('dayjs/plugin/utc');
  12. var dayjs = require('dayjs').extend(customParseFormat).extend(utc);
  13. var StreamBuf = require('../utils/stream-buf');
  14. var _require = require('../utils/utils'),
  15. exists = _require.fs.exists;
  16. /* eslint-disable quote-props */
  17. var SpecialValues = {
  18. true: true,
  19. false: false,
  20. '#N/A': {
  21. error: '#N/A'
  22. },
  23. '#REF!': {
  24. error: '#REF!'
  25. },
  26. '#NAME?': {
  27. error: '#NAME?'
  28. },
  29. '#DIV/0!': {
  30. error: '#DIV/0!'
  31. },
  32. '#NULL!': {
  33. error: '#NULL!'
  34. },
  35. '#VALUE!': {
  36. error: '#VALUE!'
  37. },
  38. '#NUM!': {
  39. error: '#NUM!'
  40. }
  41. };
  42. /* eslint-ensable quote-props */
  43. var CSV = /*#__PURE__*/function () {
  44. function CSV(workbook) {
  45. _classCallCheck(this, CSV);
  46. this.workbook = workbook;
  47. this.worksheet = null;
  48. }
  49. _createClass(CSV, [{
  50. key: "readFile",
  51. value: function () {
  52. var _readFile = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(filename, options) {
  53. var stream, worksheet;
  54. return regeneratorRuntime.wrap(function _callee$(_context) {
  55. while (1) {
  56. switch (_context.prev = _context.next) {
  57. case 0:
  58. options = options || {};
  59. _context.next = 3;
  60. return exists(filename);
  61. case 3:
  62. if (_context.sent) {
  63. _context.next = 5;
  64. break;
  65. }
  66. throw new Error("File not found: ".concat(filename));
  67. case 5:
  68. stream = fs.createReadStream(filename);
  69. _context.next = 8;
  70. return this.read(stream, options);
  71. case 8:
  72. worksheet = _context.sent;
  73. stream.close();
  74. return _context.abrupt("return", worksheet);
  75. case 11:
  76. case "end":
  77. return _context.stop();
  78. }
  79. }
  80. }, _callee, this);
  81. }));
  82. function readFile(_x, _x2) {
  83. return _readFile.apply(this, arguments);
  84. }
  85. return readFile;
  86. }()
  87. }, {
  88. key: "read",
  89. value: function read(stream, options) {
  90. var _this = this;
  91. options = options || {};
  92. return new Promise(function (resolve, reject) {
  93. var worksheet = _this.workbook.addWorksheet(options.sheetName);
  94. var dateFormats = options.dateFormats || ['YYYY-MM-DD[T]HH:mm:ssZ', 'YYYY-MM-DD[T]HH:mm:ss', 'MM-DD-YYYY', 'YYYY-MM-DD'];
  95. var map = options.map || function (datum) {
  96. if (datum === '') {
  97. return null;
  98. }
  99. var datumNumber = Number(datum);
  100. if (!Number.isNaN(datumNumber) && datumNumber !== Infinity) {
  101. return datumNumber;
  102. }
  103. var dt = dateFormats.reduce(function (matchingDate, currentDateFormat) {
  104. if (matchingDate) {
  105. return matchingDate;
  106. }
  107. var dayjsObj = dayjs(datum, currentDateFormat, true);
  108. if (dayjsObj.isValid()) {
  109. return dayjsObj;
  110. }
  111. return null;
  112. }, null);
  113. if (dt) {
  114. return new Date(dt.valueOf());
  115. }
  116. var special = SpecialValues[datum];
  117. if (special !== undefined) {
  118. return special;
  119. }
  120. return datum;
  121. };
  122. var csvStream = fastCsv.parse(options.parserOptions).on('data', function (data) {
  123. worksheet.addRow(data.map(map));
  124. }).on('end', function () {
  125. csvStream.emit('worksheet', worksheet);
  126. });
  127. csvStream.on('worksheet', resolve).on('error', reject);
  128. stream.pipe(csvStream);
  129. });
  130. }
  131. /**
  132. * @deprecated since version 4.0. You should use `CSV#read` instead. Please follow upgrade instruction: https://github.com/exceljs/exceljs/blob/master/UPGRADE-4.0.md
  133. */
  134. }, {
  135. key: "createInputStream",
  136. value: function createInputStream() {
  137. throw new Error('`CSV#createInputStream` is deprecated. You should use `CSV#read` instead. This method will be removed in version 5.0. Please follow upgrade instruction: https://github.com/exceljs/exceljs/blob/master/UPGRADE-4.0.md');
  138. }
  139. }, {
  140. key: "write",
  141. value: function write(stream, options) {
  142. var _this2 = this;
  143. return new Promise(function (resolve, reject) {
  144. options = options || {}; // const encoding = options.encoding || 'utf8';
  145. // const separator = options.separator || ',';
  146. // const quoteChar = options.quoteChar || '\'';
  147. var worksheet = _this2.workbook.getWorksheet(options.sheetName || options.sheetId);
  148. var csvStream = fastCsv.format(options.formatterOptions);
  149. stream.on('finish', function () {
  150. resolve();
  151. });
  152. csvStream.on('error', reject);
  153. csvStream.pipe(stream);
  154. var _options = options,
  155. dateFormat = _options.dateFormat,
  156. dateUTC = _options.dateUTC;
  157. var map = options.map || function (value) {
  158. if (value) {
  159. if (value.text || value.hyperlink) {
  160. return value.hyperlink || value.text || '';
  161. }
  162. if (value.formula || value.result) {
  163. return value.result || '';
  164. }
  165. if (value instanceof Date) {
  166. if (dateFormat) {
  167. return dateUTC ? dayjs.utc(value).format(dateFormat) : dayjs(value).format(dateFormat);
  168. }
  169. return dateUTC ? dayjs.utc(value).format() : dayjs(value).format();
  170. }
  171. if (value.error) {
  172. return value.error;
  173. }
  174. if (_typeof(value) === 'object') {
  175. return JSON.stringify(value);
  176. }
  177. }
  178. return value;
  179. };
  180. var includeEmptyRows = options.includeEmptyRows === undefined || options.includeEmptyRows;
  181. var lastRow = 1;
  182. if (worksheet) {
  183. worksheet.eachRow(function (row, rowNumber) {
  184. if (includeEmptyRows) {
  185. while (lastRow++ < rowNumber - 1) {
  186. csvStream.write([]);
  187. }
  188. }
  189. var values = row.values;
  190. values.shift();
  191. csvStream.write(values.map(map));
  192. lastRow = rowNumber;
  193. });
  194. }
  195. csvStream.end();
  196. });
  197. }
  198. }, {
  199. key: "writeFile",
  200. value: function writeFile(filename, options) {
  201. options = options || {};
  202. var streamOptions = {
  203. encoding: options.encoding || 'utf8'
  204. };
  205. var stream = fs.createWriteStream(filename, streamOptions);
  206. return this.write(stream, options);
  207. }
  208. }, {
  209. key: "writeBuffer",
  210. value: function () {
  211. var _writeBuffer = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(options) {
  212. var stream;
  213. return regeneratorRuntime.wrap(function _callee2$(_context2) {
  214. while (1) {
  215. switch (_context2.prev = _context2.next) {
  216. case 0:
  217. stream = new StreamBuf();
  218. _context2.next = 3;
  219. return this.write(stream, options);
  220. case 3:
  221. return _context2.abrupt("return", stream.read());
  222. case 4:
  223. case "end":
  224. return _context2.stop();
  225. }
  226. }
  227. }, _callee2, this);
  228. }));
  229. function writeBuffer(_x3) {
  230. return _writeBuffer.apply(this, arguments);
  231. }
  232. return writeBuffer;
  233. }()
  234. }]);
  235. return CSV;
  236. }();
  237. module.exports = CSV;
  238. //# sourceMappingURL=csv.js.map