Auto Column Width with ExcelJS | ATLASSC.NET
Skip to main content
/// .DATA.FRAGMENT_20221115

Auto Column Width with ExcelJS

1 minAuthor: Z.SHINCHVEN

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.
};
RackNerd Billboard Banner
Share node:
/// .RELATED.DATA_STREAMSShared tags

Related posts

Scanning_database_for_correlations…

/// .UPLINK.SUBSCRIBE

Keep your deck synced with every new transmission from ATLASSC.NET. Subscribe over RSS or Atom, or wire the whole archive straight into your AI assistant with the MCP server.