| 107 | } |
| 108 | |
| 109 | write(stream, options) { |
| 110 | return new Promise((resolve, reject) => { |
| 111 | options = options || {}; |
| 112 | // const encoding = options.encoding || 'utf8'; |
| 113 | // const separator = options.separator || ','; |
| 114 | // const quoteChar = options.quoteChar || '\''; |
| 115 | |
| 116 | const worksheet = this.workbook.getWorksheet(options.sheetName || options.sheetId); |
| 117 | |
| 118 | const csvStream = fastCsv.format(options.formatterOptions); |
| 119 | stream.on('finish', () => { |
| 120 | resolve(); |
| 121 | }); |
| 122 | csvStream.on('error', reject); |
| 123 | csvStream.pipe(stream); |
| 124 | |
| 125 | const {dateFormat, dateUTC} = options; |
| 126 | const map = |
| 127 | options.map || |
| 128 | (value => { |
| 129 | if (value) { |
| 130 | if (value.text || value.hyperlink) { |
| 131 | return value.hyperlink || value.text || ''; |
| 132 | } |
| 133 | if (value.formula || value.result) { |
| 134 | return value.result || ''; |
| 135 | } |
| 136 | if (value instanceof Date) { |
| 137 | if (dateFormat) { |
| 138 | return dateUTC |
| 139 | ? dayjs.utc(value).format(dateFormat) |
| 140 | : dayjs(value).format(dateFormat); |
| 141 | } |
| 142 | return dateUTC ? dayjs.utc(value).format() : dayjs(value).format(); |
| 143 | } |
| 144 | if (value.error) { |
| 145 | return value.error; |
| 146 | } |
| 147 | if (typeof value === 'object') { |
| 148 | return JSON.stringify(value); |
| 149 | } |
| 150 | } |
| 151 | return value; |
| 152 | }); |
| 153 | |
| 154 | const includeEmptyRows = options.includeEmptyRows === undefined || options.includeEmptyRows; |
| 155 | let lastRow = 1; |
| 156 | if (worksheet) { |
| 157 | worksheet.eachRow((row, rowNumber) => { |
| 158 | if (includeEmptyRows) { |
| 159 | while (lastRow++ < rowNumber - 1) { |
| 160 | csvStream.write([]); |
| 161 | } |
| 162 | } |
| 163 | const {values} = row; |
| 164 | values.shift(); |
| 165 | csvStream.write(values.map(map)); |
| 166 | lastRow = rowNumber; |