Created
November 15, 2019 02:36
-
-
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)
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 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