typescript 如何在Excel中自动调整列宽

wh6knrhe  于 2023-02-13  发布在  TypeScript
关注(0)|答案(5)|浏览(152)

我必须使用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函数来解决这个问题吗?
谢谢你的帮助

ylamdve6

ylamdve61#

您可以迭代单元格并检查每个单元格的长度

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;
    });
shyt4zoc

shyt4zoc2#

对我很有效,你可以这样做:

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;
  });
}
k4emjkb1

k4emjkb13#

Ashish的回答起作用了谢谢
如果第一个单元格中有,则忽略序列号:
参考:

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;
    }
});
mbzjlibv

mbzjlibv4#

我的回答可能来得有点晚,但我希望这能有所帮助。上面的例子工作得很好。只是做了一点修改,以确保一切正常工作。为了防止用s覆盖列,这是我的工作方式

worksheet.columns.forEach(function (column) {
              var dataMax = 0;
              column.eachCell({ includeEmpty: true }, function (cell) { 
                dataMax = cell.value?cell.value.toString().length:0;
                if(dataMax <= (column.header.length+2) ){
                    if(column.width > dataMax){
                        //retain its default width
                    } else {
                        column.width = column.header.length+3;
                    }
                } else {
                    column.width = dataMax+3;
                   column.header.length = dataMax+3;
                }
                dataMax = 0;
              })
              
            });
gjmwrych

gjmwrych5#

如果您发现其他解决方案在涉及numFmt时不起作用,特别是对于Date值,那么这里有一个解决方案,它使用前面建议的一些概念,以及SSF库,在获取长度之前用numFmt化单元格值。

import { format } from 'ssf';

// Convert Date object to Microsoft serial date aka ms date aka OA date
const dateToSerial = (date: Date): number => {
  const timezoneOffset = date.getTimezoneOffset() / (60 * 24);
  const msDate = date.getTime() / 86400000 + (25569 - timezoneOffset);
  return msDate;
};

const autoFitColumn = (column: ExcelJS.Column) => {
  const numFmt = column.numFmt;
  let maxLength = 6;
  column.eachCell({ includeEmpty: true }, (cell: ExcelJS.Cell) => {
    let columnLength: number;
    if (numFmt && cell.value != undefined) {
      switch (cell.type) {
        case ExcelJS.ValueType.Date:
          const serialDate = dateToSerial(cell.value as Date);
          const formattedDate = format(numFmt, serialDate);
          columnLength = formattedDate.length;
          break;
        case ExcelJS.ValueType.Number:
          const formattedNumber = format(numFmt, cell.value as Number);
          columnLength = formattedNumber.length;
          break;
        default:
          const formatted = format(numFmt, cell.value);
          columnLength = formatted.length;
          break;
      }
    } else {
      columnLength = cell.text.length;
    }
    maxLength = Math.max(maxLength, columnLength);
  });
  column.width = maxLength + 2;
};

相关问题