-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerate-excel.ts
More file actions
70 lines (60 loc) · 2.66 KB
/
generate-excel.ts
File metadata and controls
70 lines (60 loc) · 2.66 KB
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
import { faker } from '@faker-js/faker';
import ExcelJS from 'exceljs';
import { Worker, isMainThread, parentPort, workerData } from 'worker_threads';
import os from 'os';
import fs from 'fs';
// Constants
const NUM_COLUMNS = 100;
const NUM_ROWS = 1_000_000;
const FILE_NAME = 'fakeData.xlsx';
const NUM_WORKERS = Math.max(1, os.cpus().length - 1);
const ROWS_PER_WORKER = Math.ceil(NUM_ROWS / NUM_WORKERS);
if (!isMainThread) {
const { startRow, endRow, columns } = workerData;
const rows = [];
for (let i = startRow; i < endRow; i++) {
const rowData: { [key: string]: any } = {};
columns.forEach((col: { key: string | number; }, index: number) => {
rowData[col.key] = index === 0 ? faker.lorem.sentence() : faker.finance.accountName();
});
rows.push(rowData);
}
parentPort?.postMessage(rows);
} else {
async function generateExcel() {
try {
const workbook = new ExcelJS.stream.xlsx.WorkbookWriter({ filename: FILE_NAME, useStyles: true });
const worksheet = workbook.addWorksheet('Fake Data');
const columns = Array.from({ length: NUM_COLUMNS }, (_, i) => ({
header: `Column ${i + 1}`,
key: `column${i + 1}`,
width: 15
}));
worksheet.columns = columns;
const workerPromises = Array.from({ length: NUM_WORKERS }, (_, i) => {
const startRow = i * ROWS_PER_WORKER;
const endRow = Math.min(startRow + ROWS_PER_WORKER, NUM_ROWS);
return new Promise<any[]>((resolve, reject) => {
const worker = new Worker(__filename, {
workerData: { startRow, endRow, columns }
});
worker.on('message', resolve);
worker.on('error', reject);
});
});
const results = await Promise.all(workerPromises);
results.flat().forEach(rowData => worksheet.addRow(rowData).commit());
await workbook.commit();
const stats = fs.statSync(FILE_NAME);
const fileSizeInBytes = stats.size;
const fileSizeInMB = fileSizeInBytes / (1024 * 1024);
const fileSizeInGB = fileSizeInMB / 1024;
console.log(`Excel file generated: ${FILE_NAME}`);
console.log(`Total number of rows: ${worksheet.rowCount}`);
console.log(`File size: ${fileSizeInMB.toFixed(2)} MB (${fileSizeInGB.toFixed(2)} GB)`);
} catch (error) {
console.error("An error occurred during Excel file generation:", error);
}
}
generateExcel().catch(console.error);
}