-
-
Save darkterminal/a97e9d76cc6f4784a9ce8981bb021402 to your computer and use it in GitHub Desktop.
Export from JavaScript to Excel (xlsx)
This file contains 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 path = require('path'); | |
const exportExcel = (data, workSheetColumnNames, workSheetName, filePath) => { | |
const workBook = xlsx.utils.book_new(); | |
const workSheetData = [ | |
workSheetColumnNames, | |
... data | |
]; | |
const workSheet = xlsx.utils.aoa_to_sheet(workSheetData); | |
xlsx.utils.book_append_sheet(workBook, workSheet, workSheetName); | |
xlsx.writeFile(workBook, path.resolve(filePath)); | |
} | |
const exportUsersToExcel = (users, workSheetColumnNames, workSheetName, filePath) => { | |
const data = users.map(user => { | |
return [user.id, user.name, user.age]; | |
}); | |
exportExcel(data, workSheetColumnNames, workSheetName, filePath); | |
} | |
module.exports = exportUsersToExcel; |
This file contains 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 exportUsersToExcel = require('./exportService'); | |
const users = [ | |
{ | |
id: 0, | |
name: 'Peter', | |
age: 31 | |
}, | |
{ | |
id: 1, | |
name: 'John', | |
age: 23 | |
} | |
]; | |
const workSheetColumnName = [ | |
"ID", | |
"Name", | |
"Age" | |
] | |
const workSheetName = 'Users'; | |
const filePath = './outputFiles/excel-from-js.xlsx'; | |
exportUsersToExcel(users, workSheetColumnName, workSheetName, filePath); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment