我必须使用exceljs
自动调整列宽。我的excel必须是动态的,并且在Excel中只保存用户将在请求中提供的列。对于这种情况,我提供以下语法:
workSheet.getRow(1).values = dto.columns;
它使用dto.columns
中提供的名称将列名保存在第一行上。
但是我必须为每一列设置宽度,我尝试这样做:
for(let i=0; i <= dto.columns.length-1; i++) {
workSheet.columns = [
{key: dto.columns[i], width: Object.keys(dto.columns[i]).length}
]
}
但这并没有给我任何设置:
谁能告诉我如何创建一个autosize
函数来解决这个问题?
谢谢你的帮助
发布于 2020-09-28 15:31:29
迭代单元格并以这种方式检查每个单元格的长度
worksheet.columns.forEach(function (column, i) {
var maxLength = 0;
column["eachCell"]({ includeEmpty: true }, function (cell) {
var columnLength = cell.value ? cell.value.toString().length : 10;
if (columnLength > maxLength ) {
maxLength = columnLength;
}
});
column.width = maxLength < 10 ? 10 : maxLength;
});
发布于 2021-09-22 16:15:22
它对我来说很有效,你可以这样做:
private AdjustColumnWidth(worksheet) {
worksheet.columns.forEach(column => {
const lengths = column.values.map(v => v.toString().length);
const maxLength = Math.max(...lengths.filter(v => typeof v === 'number'));
column.width = maxLength;
});
}
发布于 2021-05-17 20:49:33
阿什什的答案是有效的。谢谢
如果在第一个单元格中有,则忽略序列号:
请参阅:
worksheet.columns.forEach(function (column, i) {
if(i!==0)
{
var maxLength = 0;
column["eachCell"]({ includeEmpty: true }, function (cell) {
var columnLength = cell.value ? cell.value.toString().length : 10;
if (columnLength > maxLength ) {
maxLength = columnLength;
}
});
column.width = maxLength < 10 ? 10 : maxLength;
}
});
https://stackoverflow.com/questions/63189741
复制相似问题