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

巧了我就是萌 提交于 2019-12-02 20:20:04

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

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.

public exportAsExcelFile(json: any[], excelFileName: string): void {

const header = Object.keys(json[0]); // columns name

var wscols = [];
for (var i = 0; i < header.length; i++) {  // columns length added
  wscols.push({ wch: header[i].length + 5 })
}
const worksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(json);
worksheet["!cols"] = wscols;

}

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!