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

我只是一个虾纸丫 提交于 2019-12-20 09:51:05

问题


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


回答1:


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;



回答2:


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



回答3:


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.




回答4:


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;
}


来源:https://stackoverflow.com/questions/24395693/how-to-set-cell-width-when-export-xlsx-files-with-js-xlsx

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