How to set cell width when export .xlsx files with js-xlsx

I found a snippet the the write test here https://github.com/SheetJS/js-xlsx/blob/master/tests/write.js#L14-L19

For quick reference, where ws is your worksheet.

var wscols = [
    {wch:6},
    {wch:7},
    {wch:10},
    {wch:20}
];

ws['!cols'] = wscols;

Similar to cell width, you can set the cell height in the following way

var wsrows =  [
                 {hpt: 12}, // row 1 sets to the height of 12 in points
                 {hpx: 16}, // row 2 sets to the height of 16 in pixels
               ];

ws['!rows'] = wsrows; // ws - worksheet

Hint: If your worksheet data is auto generated and you don't know how many rows and columns are get populated then you could use the following way to find the number of rows and columns in the worksheet for doing cell width/height formatting.

var range = XLSX.utils.decode_range(ws['!ref']);
var noRows = range.e.r; // No.of rows
var noCols = range.e.c; // No. of cols

Nothing new, but explicitly using the width property makes it a bit easier to maintain:

ws['!cols'] = [{ width: 20 }, { width: 20 }, { width: 150 } ]; //set col. widths

Here is the full list of properties you can give to these ColInfo objects though, they give reasons why each width exists, but they state you should use width > wpx > wch, depending on the type of sheet you have and what is available for your use case. More can be read here: https://docs.sheetjs.com/ enter image description here


Extending the question, if you need to set automatic width base on your content, you can write as following:

const worksheet = XLSX.utils.aoa_to_sheet(arrayOfArray);
worksheet['!cols'] = fitToColumn(arrayOfArray);

function fitToColumn(arrayOfArray) {
    // get maximum character of each column
    return arrayOfArray[0].map((a, i) => ({ wch: Math.max(...arrayOfArray.map(a2 => a2[i] ? a2[i].toString().length : 0)) }));
}

This function assumes your first row has most columns. It then tries to find the widest cell in each column by calculating content character length.