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

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;


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.


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 rowsvar noCols = range.e.c; // No. of cols