Created
February 16, 2023 08:29
-
-
Save fwindpeak/a8d50ed67e8a05a625462c3a03b95532 to your computer and use it in GitHub Desktop.
Combine multiple xlsx files with consistent structure into one
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
const xlsx = require('xlsx'); | |
const glob = require('glob'); | |
let result = []; | |
const readXlsx = (filePath) => { | |
const wb = xlsx.readFile(filePath); | |
for (let sheetName of wb.SheetNames) { | |
const sheet = wb.Sheets[sheetName]; | |
const data = xlsx.utils.sheet_to_json(sheet); | |
// console.log(data); | |
result = [...result, ...data]; | |
} | |
}; | |
const writeXlsx = (filePath) => { | |
const workBook = xlsx.utils.book_new(); | |
const sheet = xlsx.utils.json_to_sheet(result); | |
console.log(sheet); | |
xlsx.utils.book_append_sheet(workBook, sheet, 'sheet1'); | |
xlsx.writeFile(workBook, filePath); | |
// console.log(workBook); | |
}; | |
glob('doc/**/*.xlsx', (error, files) => { | |
console.log('files', files); | |
for (let file of files) { | |
console.log('file', file); | |
readXlsx(file); | |
} | |
console.log('result', result); | |
writeXlsx('./result.xlsx', (res) => { | |
console.log(res); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment