avatar

ShīnChvën ✨

Effective Accelerationism

Powered by Druid

Auto Column Width with ExcelJS

Mon Nov 14 2022

Auto-fit column width with ExcelJS is easy, but it consumes a lot of time if your dataset is large.

import ExcelJS, {Worksheet} from "exceljs";

/**
 * Auto-fit column's width
 *
 * @param worksheet {ExcelJS.Worksheet}
 * @param minimalWidth
 */
export const autoFitColumnWidth = (worksheet: Worksheet, minimalWidth = 10) => {
  worksheet.columns.forEach((column) => {
    let maxColumnLength = 0;
    if (column && typeof column.eachCell === 'function') {
      column.eachCell({includeEmpty: true}, (cell) => {
        maxColumnLength = Math.max(
          maxColumnLength,
          minimalWidth,
          cell.value ? cell.value.toString().length : 0
        );
      });
      column.width = maxColumnLength + 2;
    }
  });
  return worksheet; // for chaining.
};