---
title: "Auto Column Width with ExcelJS"
date: 2022-11-14T15:25:44.000Z
author: Z.SHINCHVEN
tags: [ExcelJS]
canonical: https://atlassc.net/2022/11/15/auto-column-width-with-exceljs
---
Auto-fit column width with `ExcelJS` is easy, but it consumes a lot of time if your dataset is large.

```ts
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.
};
```
