-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathparser.ts
321 lines (274 loc) · 8.28 KB
/
parser.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
/* global Office */
import * as ExcelAPI from './excel';
import {Shape} from './excel';
import * as Papa from 'papaparse';
export const enum InputType {
file = 'File',
text = 'Text input',
}
export interface Source {
inputType: InputType;
file?: File;
text: string;
}
type Config = Pick<Papa.ParseLocalConfig, 'delimiter' | 'encoding' | 'chunk' | 'complete'>;
export const enum NewlineSequence {
AutoDetect = '',
CRLF = '\r\n',
CR = '\r',
LF = '\n',
}
export interface ImportOptions extends Config {
source: Source;
newline: NewlineSequence;
numberFormat: NumberFormat;
}
export interface ExportOptions {
delimiter: string;
newline: NewlineSequence;
}
export const enum NumberFormat {
Text = '@',
General = 'General',
}
let reduceChunkSize = null;
export class Parser {
constructor() {
this.abortFlag = new AbortFlag();
}
async init(): Promise<Office.PlatformType> {
const platform = await ExcelAPI.init();
if (platform === Office.PlatformType.OfficeOnline) {
// Online API can throw error if request size is too large
reduceChunkSize = true;
(Papa.LocalChunkSize as unknown as number) = 10_000;
} else {
reduceChunkSize = false;
}
return platform;
}
async importCSV(
importOptions: ImportOptions,
progressCallback: ProgressCallback,
): Promise<Papa.ParseError[]> {
this.abort();
let errors = null;
await ExcelAPI.runOnBlankWorksheet(async (worksheet) => {
const chunkProcessor = new ChunkProcessor(worksheet, progressCallback, this.abortFlag);
errors = await chunkProcessor.run(importOptions);
});
return errors;
}
async csvStringAndName(
exportOptions: ExportOptions,
progressCallback: ProgressCallback,
): Promise<CsvStringAndName> {
this.abort();
let namesAndShape = null;
let resultString = '';
await ExcelAPI.runOnCurrentWorksheet(async (worksheet) => {
namesAndShape = await ExcelAPI.worksheetNamesAndShape(worksheet);
worksheet.context.application.suspendApiCalculationUntilNextSync();
resultString = await csvString(
worksheet,
namesAndShape.shape,
chunkRows(namesAndShape.shape),
exportOptions,
progressCallback,
this.abortFlag,
);
});
return {
name: nameToUse(namesAndShape.workbookName, namesAndShape.worksheetName),
string: resultString,
};
}
abort(): void {
this.abortFlag.abort();
this.abortFlag = new AbortFlag();
}
private abortFlag: AbortFlag;
}
export class AbortFlag {
public constructor() {
this._aborted = false;
}
public abort(): void {
this._aborted = true;
}
public aborted(): boolean {
return this._aborted;
}
private _aborted: boolean;
}
type ProgressCallback = (progress: number) => void;
export class ChunkProcessor {
public constructor(
worksheet: Excel.Worksheet,
progressCallback: ProgressCallback,
abortFlag: AbortFlag,
) {
this._worksheet = worksheet;
this._progressCallback = progressCallback;
this._abortFlag = abortFlag;
this._currRow = 0;
this._currentProgress = 0.0;
}
public run(importOptions: ImportOptions): Promise<Papa.ParseError[]> {
this._progressCallback(0.0);
this._progressPerChunk = ChunkProcessor.progressPerChunk(
importOptions.source,
Papa.LocalChunkSize as unknown as number,
);
this._numberFormat = importOptions.numberFormat;
return new Promise((resolve) => {
importOptions.chunk = this.chunk;
importOptions.complete = results => resolve(results.errors);
switch (importOptions.source.inputType) {
case InputType.file:
Papa.parse(importOptions.source.file, importOptions as Papa.ParseLocalConfig);
break;
case InputType.text:
Papa.parse(
/* eslint-disable @typescript-eslint/no-explicit-any */
importOptions.source.text as any,
importOptions as Papa.ParseLocalConfig,
);
break;
}
});
}
private static progressPerChunk(source: Source, chunkSize: number): number {
switch (source.inputType) {
case InputType.file:
if (source.file.size === 0) {
return 1.0;
}
return chunkSize / source.file.size;
case InputType.text:
if (source.text.length === 0) {
return 1.0;
}
return chunkSize / source.text.length;
}
}
private readonly _worksheet: Excel.Worksheet;
private readonly _progressCallback: ProgressCallback;
private readonly _abortFlag: AbortFlag;
private readonly _excelAPI = ExcelAPI;
private _currRow: number;
private _progressPerChunk: number;
private _currentProgress: number;
private _numberFormat: NumberFormat;
private chunk = (chunk: Papa.ParseResult<string[]>, parser: Papa.Parser) => {
if (this._abortFlag.aborted()) {
parser.abort();
}
this._worksheet.context.application.suspendApiCalculationUntilNextSync();
this._excelAPI.setChunk(this._worksheet, this._currRow, chunk.data, this._numberFormat);
this._currRow += chunk.data.length;
parser.pause();
// sync() must be called after each chunk, otherwise API may throw exception
this._worksheet.context.sync().then(parser.resume);
// Since the Excel API is so damn slow, updating GUI every chunk has a negligible impact
// on performance.
this._progressCallback(this._currentProgress += this._progressPerChunk);
};
}
/*
RFC 4180 standard:
MS-DOS-style lines that end with (CR/LF) characters (optional for the last line).
An optional header record (there is no sure way to detect whether it is present, so care is required
when importing).
Each record "should" contain the same number of comma-separated fields.
Any field may be quoted (with double quotes).
Fields containing a line-break, double-quote or commas (delimiter) should be quoted. (If they are
not, the file will likely be impossible to process correctly).
A (double) quote character in a field must be represented by two (double) quote characters.
Thanks Wikipedia.
*/
export function chunkRange(
chunk: number,
shape: Shape,
chunkRows: number,
): {startRow: number; startColumn: number; rowCount: number; columnCount: number} {
return {
startRow: chunk * chunkRows,
startColumn: 0,
rowCount: Math.min(chunkRows, shape.rows),
columnCount: shape.columns,
};
}
export function addQuotes(row: string[], delimiter: string): void {
if (delimiter == '') {
return;
}
const charactersToWatchOutFor = ['\r', '\n', '\u0022' /* double quote */, delimiter];
for (let i = 0; i < row.length; i++) {
if (charactersToWatchOutFor.some(c => row[i].includes(c))) {
row[i] = '\u0022' + row[i].replace(/\u0022/g, '\u0022\u0022') + '\u0022';
}
}
}
/* eslint-disable @typescript-eslint/no-explicit-any */
export function rowString(row: any[], exportOptions: Readonly<ExportOptions>): string {
const stringValues = row.map(a => a.toString());
addQuotes(stringValues, exportOptions.delimiter);
return stringValues.join(exportOptions.delimiter) + exportOptions.newline;
}
export function chunkString(values: any[][], exportOptions: Readonly<ExportOptions>): string {
let result = '';
for (let i = 0; i < values.length; i++) {
result += rowString(values[i], exportOptions);
}
return result;
}
/* eslint-enable @typescript-eslint/no-explicit-any */
export async function csvString(
worksheet: Excel.Worksheet,
shape: Shape,
chunkRows: number,
exportOptions: Readonly<ExportOptions>,
progressCallback: ProgressCallback,
abortFlag: AbortFlag,
): Promise<string> {
let result = '';
// chunkRows is never 0
for (let chunk = 0; chunk < Math.ceil(shape.rows / chunkRows); chunk++) {
if (abortFlag.aborted()) {
break;
}
// shape.rows is never 0
progressCallback(chunk * chunkRows / shape.rows);
const chunkRange_ = chunkRange(chunk, shape, chunkRows);
const range = worksheet.getRangeByIndexes(
chunkRange_.startRow,
chunkRange_.startColumn,
chunkRange_.rowCount,
chunkRange_.columnCount,
).load('values');
await worksheet.context.sync();
result += chunkString(range.values, exportOptions);
}
return result;
}
export function nameToUse(workbookName: string, worksheetName: string): string {
if (/^Sheet\d+$/.test(worksheetName)) { // 'Sheet1' isn't a good name to use
// Workbook name usually includes the file extension
const to = workbookName.lastIndexOf('.');
return workbookName.substr(0, to === -1 ? workbookName.length : to);
} else {
return worksheetName;
}
}
function chunkRows(shape: Shape): number {
if (reduceChunkSize) {
return Math.floor(10_000 / shape.columns);
} else {
return shape.rows;
}
}
export interface CsvStringAndName {
name: string;
string: string;
}