问题描述
在使用js-xlsx导出.xlsx文件时,我想将列宽设置为等于该列内容的最大长度
预期
private autofitColumns(json:any [],工作表:XLSX.WorkSheet,标头?:string []){const jsonKeys =标头?标头:Object.keys(json [0]);让objectMaxLength = [];for(让i = 0; i< json.length; i ++){让值= json [i];for(让j = 0; j< jsonKeys.length; j ++){if(typeof value [jsonKeys [j]] ==数字"){objectMaxLength [j] = 10;} 别的 {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]> =键[j] .length?objectMaxLength [j]:键[j] .length;}}const wscols = objectMaxLength.map(w => {return {width:w}});worksheet [!cols"] = wscols;
}
来自 https://github.com/SheetJS/sheetjs/issues/1473#issuecomment-580648494
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
Expected
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
这篇关于使用js-xlsx导出.xlsx文件时,如何根据内容设置整个列的宽度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!