Articles in this section
Category / Section

How to adjust the width of columns in a JavaScript Spreadsheet based on their content

1 min read

This knowledge base explains how to adjust the width of columns in a JavaScript Spreadsheet based on their content. Use the autoFit method to achieve this requirement. Construct the active sheet’s used column range by invoking the getColumnHeaderText function and providing it to the autoFit method as an argument.

[HTML]

 <div id="spreadsheet"></div>

[TS]

let spreadsheet: Spreadsheet = new Spreadsheet({
 sheets: [
   {
     name: 'Car Sales Report',
     ranges: [{ dataSource: (dataSource as any).defaultData }]
   }
 ],

created: (): void => {
    // Applies cell and number formatting to specified range of the active sheet
      spreadsheet.cellFormat(
     { fontWeight: 'bold', textAlign: 'center', verticalAlign: 'middle' },
     'A1:F1'
     );
   // Get the current sheet's used range.
   let usedRange: UsedRangeModel = spreadsheet.getActiveSheet().usedRange;
   // Get the used column range using the getColumnHeaderText method.
   let columnRange: string =
     getColumnHeaderText(1) +
     ':' +
     getColumnHeaderText(usedRange.colIndex + 1);

  // To auto fit the used column width based on the content width.
     spreadsheet.autoFit(columnRange);
 }
});

spreadsheet.appendTo('#spreadsheet');

Sample Link: https://stackblitz.com/edit/zi7rep-xqfa6b?file=index.ts

Screenshot:

autofit.png

API Reference:

https://ej2.syncfusion.com/documentation/api/spreadsheet#autofit

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please  to leave a comment
Access denied
Access denied