JavaScript Answers

How to set cell width when export .xlsx files with Node js-xlsx?

Spread the love

To set cell width when export .xlsx files with Node js-xlsx, we set the wch property.

For instance, we write

const fitToColumn = (arrayOfArray) => {
  return arrayOfArray[0].map((a, i) => ({
    wch: Math.max( => (a2[i] ? a2[i].toString().length : 0))

const worksheet = XLSX.utils.aoa_to_sheet(arrayOfArray);
worksheet["!cols"] = fitToColumn(arrayOfArray);

to define the fitToColumn function that returns an array with objects with the wch property that has the width value.

We set the width to the max number of characters in the cell of each column.

We get the worksheet from the aoa_to_sheet called with our arrayOfArray nested array of data.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.