繁体   English   中英

使用js-xlsx导出.xlsx文件时,如何根据内容设置整列的宽度?

[英]How to set the width of the entire column based on the content when export .xlsx files with js-xlsx?

使用 js-xlsx 导出 .xlsx 文件时,我想将列宽设置为等于该列内容的最大长度

使用 js-xlsx 导出 .xlsx 文件时如何设置单元格宽度

我试过上面。

let sheet = workBook.Sheets.Sheet1;
let wscols = [];
const colNode = table.tHead.rows[0].childNodes; // getting the column names from the table rendered on the page
const colNumber = colNode.length;
for(let i = 0; i < colNumber; i++){
    wscols.push({
        wch: colNode[i].innerText.length * 1.28
    })
}
sheet['!cols'] = wscols;

我可以通过从屏幕上呈现的表格中获取列的名称来设置宽度。 但是我遇到的问题是,假设列名的名称是“Title”,并且其行具有一些类似于“Australia”的值,那么列名的长度较小,并且整个列的宽度设置不正确。

实际的在此处输入图片说明

预期的在此处输入图片说明

private autofitColumns(json: any[], worksheet: XLSX.WorkSheet, header?: string[]) {

const jsonKeys = header ? header : Object.keys(json[0]);

let objectMaxLength = []; 
for (let i = 0; i < json.length; i++) {
  let value = json[i];
  for (let j = 0; j < jsonKeys.length; j++) {
    if (typeof value[jsonKeys[j]] == "number") {
      objectMaxLength[j] = 10;
    } else {

      const l = value[jsonKeys[j]] ? value[jsonKeys[j]].length : 0;

      objectMaxLength[j] =
        objectMaxLength[j] >= l
          ? objectMaxLength[j]
          : l;
    }
  }

  let key = jsonKeys;
  for (let j = 0; j < key.length; j++) {
    objectMaxLength[j] =
      objectMaxLength[j] >= key[j].length
        ? objectMaxLength[j]
        : key[j].length;
  }
}

const wscols = objectMaxLength.map(w => { return { width: w} });

worksheet["!cols"] = wscols;

}

来自https://github.com/SheetJS/sheetjs/issues/1473#issuecomment-580648494

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM