Created
April 29, 2021 08:54
-
-
Save pmdroid/3e408d66fcbcd99dc4cc9cec6483db3e to your computer and use it in GitHub Desktop.
xlsx to json parsing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as _ from 'lodash'; | |
import * as csv from 'fast-csv'; | |
import * as ExcelJS from 'exceljs'; | |
export interface Column { | |
key: string; | |
header: string; | |
} | |
export async function xlsxToJSON<T>(filePath: string, columns: Partial<Column>[]): Promise<T[]> { | |
const workbook = new ExcelJS.Workbook(); | |
await workbook.xlsx.readFile(filePath); | |
const buffer = await workbook.csv.writeBuffer(); | |
const items: T[] = []; | |
return new Promise((resolve, reject) => | |
csv | |
.parseString(buffer.toString(), { headers: true }) | |
.transform((data) => { | |
return Object.keys(data).reduce((item, header) => { | |
const column = columns.find((column) => column.header === header); | |
if (column && column.key) { | |
item[column.key] = data[header]; | |
} | |
return item; | |
}, {}); | |
}) | |
.on('error', (error) => reject(error)) | |
.on('data', (row) => items.push(row)) | |
.on('end', () => resolve(items.filter((item) => !_.isEmpty(item)))), | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment