Skip to content

Instantly share code, notes, and snippets.

@burdukowsky
Created November 15, 2019 02:36
Show Gist options
  • Save burdukowsky/c13414966fa44b76b55664181ee44b07 to your computer and use it in GitHub Desktop.
Save burdukowsky/c13414966fa44b76b55664181ee44b07 to your computer and use it in GitHub Desktop.
Set column width to "fit" data for SheetJS work sheet (https://www.npmjs.com/package/xlsx)
const removeDuplicatesInArray = array => {
return array.filter((elem, pos) => array.indexOf(elem) === pos);
};
const applyAutoWidth = (XLSXWorkSheet, widthMultiplier) => {
widthMultiplier = widthMultiplier || 1.25;
const cellsKeys = Object.keys(XLSXWorkSheet).filter(key => key.match(/^[A-Z]+\d+$/)),
columns = removeDuplicatesInArray(cellsKeys.map(key => key.replace(/\d/g, '')));
const getMaxLengthOfColumn = column => {
const regExp = new RegExp('^' + column + '\\d+$'),
keysOfColumn = cellsKeys.filter(key => key.match(regExp));
return keysOfColumn.reduce((max, key) => {
const cellLength = (XLSXWorkSheet[key].v + '').length;
return cellLength > max ? cellLength : max;
}, 0);
};
if (XLSXWorkSheet['!cols'] == null) {
XLSXWorkSheet['!cols'] = [];
}
columns.forEach((column, index) => {
if (XLSXWorkSheet['!cols'][index] == null) {
XLSXWorkSheet['!cols'][index] = {};
}
Object.assign(XLSXWorkSheet['!cols'][index], {width: getMaxLengthOfColumn(column) * widthMultiplier});
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment