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

后端 未结 6 1385
南笙
南笙 2021-02-01 14:50

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

6条回答
  •  渐次进展
    2021-02-01 15:27

    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].toString().length)) }));
    }
    

    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.

提交回复
热议问题