Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
315 views
in Technique[技术] by (71.8m points)

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

I want to set column width equal to maximum length of the content of that column when exporting .xlsx files with js-xlsx

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

I tried with above.

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;

I'm able to set the width by fetching the name of column from the table rendered on the screen. But problem I'm getting is that suppose the name of column name is "Title" and its rows have some value like "Australia" then length of column name is less and the whole column width are not properly set.

Actual enter image description here

Expected enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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;

}

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...