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

时间:2019-06-25 12:14:12

标签: javascript xlsx js-xlsx sheetjs

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

How to set cell width when export .xlsx files with js-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”,则列名的长度较小,并且整个列宽均未正确设置。

实际 enter image description here

预期 enter image description here

1 个答案:

答案 0 :(得分:1)

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