Skip to content

Instantly share code, notes, and snippets.

@chetbis
Last active May 5, 2019 15:21
Show Gist options
  • Save chetbis/b20a5eb1cda1900822d9facf625e6e05 to your computer and use it in GitHub Desktop.
Save chetbis/b20a5eb1cda1900822d9facf625e6e05 to your computer and use it in GitHub Desktop.
simple demonstration of how to use xlsx-populate
(function () {
var users = [
['John Doe', 23, '9550511496'],
['Jane Doe', 22, '4444444444'],
['Jonny Doe', 24, '555599939']
],
columnHeaders = [
{ headerName: 'Name' },
{ headerName: 'Age' },
{ headerName: 'Phone Number' }
];
makeExcelSheet();
//////////////////////////////
function makeExcelSheet() {
XlsxPopulate.fromBlankAsync()
.then(function (workbook) {
defineColumnHeaders(workbook, 'Sheet1', 'A2', columnHeaders);
// populating sheet starting at cell A3
populateSheet(workbook, 'Sheet1', 'A3', users);
saveWorkBookToFile(workbook);
});
}
/**
* @param {Object} workbook
* @param {string} sheetname
* @param {string} startingCellAddress
* @param {Object[]} headers
*/
function defineColumnHeaders(workbook, sheetname, startingCellAddress, headers) {
/**
* headers should be in this format
* [ { headerName: '' } ]
*/
var startingCell = workbook
.sheet(sheetname)
.cell(startingCellAddress);
headers.forEach(function (val, index) {
startingCell.relativeCell(0, index)
.value(val.headerName)
.style('bold', true);
});
}
/**
*
* @param {Object} workbook
* @param {string} sheetname
* @param {string} startingCellAddress
* @param {Object[][]} data a two-dimensional array containing data
*/
function populateSheet(workbook, sheetname, startingCellAddress, data) {
var startingCell = workbook
.sheet(sheetname)
.cell(startingCellAddress);
data.forEach(function (datum, datumIndex) {
datum.forEach(function (fieldValue, fieldIndex) {
startingCell.relativeCell(datumIndex, fieldIndex)
.value(fieldValue);
});
});
}
/**
* @param {Object} workbook workbook to export
*/
function saveWorkBookToFile(workbook) {
workbook.outputAsync('Blob')
.then(function (excelBlob) {
saveAs(excelBlob, 'sample-excel.xlsx');
});
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment