How to adjust the width and height of a JavaScript Spreadsheet based on the number of rows and columns rendered
This knowledge base explains you how to adjust the width and height of a JavaScript Spreadsheet based on the number of rows and columns used. On the created event, fetch the used range of the sheet and update the rowCount and colCount to be rendered in the sheetModel. On the user-defined function, fetch the client-width / client-height of sheet content and main panel elements. After that, calculate and update the width / height of the rendered columns / rows using setColumnsWidth and setRowsHeight methods respectively.
[index.html]
<div id="spreadsheet"></div>
[index.ts]
import { Spreadsheet, UsedRangeModel } from '@syncfusion/ej2-spreadsheet';
import * as dataSource from './default-data.json';
let spreadsheet: Spreadsheet = new Spreadsheet({
// Specify the scroll settings for finite mode.
scrollSettings: {
isFinite: true,
enableVirtualization: false,
},
sheets: [
{
name: 'Car Sales Report',
ranges: [{ dataSource: (dataSource as any).defaultData }],
},
],
created: (): void => {
spreadsheet.cellFormat(
{ fontWeight: 'bold', textAlign: 'center', verticalAlign: 'middle' },
'A1:F1'
);
// Get the used range of the sheet.
let usedRange: UsedRangeModel = spreadsheet.sheets[0].usedRange;
// To set the rowCount/colCount in the sheet model.
spreadsheet.sheets[0].colCount = usedRange.colIndex;
spreadsheet.sheets[0].rowCount = usedRange.rowIndex;
// To update height/width to of the rendered rows/columns.
fitPage();
// Update height/width while resizing.
window.addEventListener('resize', fitPage);
},
});
function fitPage() {
// Fetch the client width of the sheet content.
let sheetWidth: number =
spreadsheet.element.querySelector('.e-sheet-content').clientWidth;
// Get the used range of the sheet.
let usedRange: UsedRangeModel = spreadsheet.sheets[0].usedRange;
// Calculate the width to be updated for each column.
let width: number = Math.floor(sheetWidth / usedRange.colIndex);
// Set width to the rendered columns.
spreadsheet.setColumnsWidth(width);
// Fetch the client height of the sheet content.
let sheetHeight: number =
spreadsheet.element.querySelector('.e-main-panel').clientHeight;
// Calculate the height to be updated for each row.
let height: number = Math.floor(sheetHeight / usedRange.rowIndex);
// Set height to the rendered rows.
spreadsheet.setRowsHeight(height);
}
spreadsheet.appendTo('#spreadsheet');
Stackblitz Sample: https://stackblitz.com/edit/gzvkh4-jaabcu?file=index.ts
Output:
For more details, please refer the following references.
https://ej2.syncfusion.com/documentation/spreadsheet/getting-started
https://ej2.syncfusion.com/documentation/spreadsheet/scrolling#finite-scrolling-with-defined-rows-and-columns
https://ej2.syncfusion.com/documentation/spreadsheet/rows-and-columns#size