I am trying to set a fixed column/cell width to my exported excel files with js-xlsx.
EDIT:
Here is the source of js-xlsx: https://github.com/SheetJS/js-xlsx
I used @Icycool 's answer as great example. I also upvoted that one as it was very useful for me.
I enhanced it a bit with a configurable default width if the content is smaller than the title and added a buffer so that it doesn't look crammed together.
Added comments and expanded to increase readability
return Object.keys(dataSource[0][0]).map((key) => {
return ({
//pick the data value that has the most content
wch: Math
.max(...dataSource[0]
//Iterate over the column object and return a width for each one
.map((dataObj: any) => {
//Return the width as the number of chars with a buffer
let keyWidth = key.toString().length
let width = dataObj[key]?.toString().length ?? defaultColumnWidth
width = width + columnWidthBuffer
//use a default with if it's smaller than the title
if (width < keyWidth) {
width = keyWidth
}
return width
})
)
})
});