Category / Section
How to get a collection of all merged range cell addresses in a React Spreadsheet
3 mins read
This article explains, how to get a collection of all merged range cell addresses in a React Spreadsheet. The spreadsheet cell model maintains the colSpan and rowSpan properties for merged cells. By using those properties and getColumnHeaderText method, you can construct the merged range collections.
[index.js]
import * as React from 'react';
import { createRoot } from 'react-dom/client';
import {
SpreadsheetComponent,
getColumnHeaderText,
} from '@syncfusion/ej2-react-spreadsheet';
import './index.css';
function App() {
let spreadsheet;
const onCreated = () => {
// Merge the cells on initial load.
spreadsheet.merge('A1:B1');
spreadsheet.merge('E1:E4');
spreadsheet.merge('F1:G4');
spreadsheet.merge('A3:D4');
spreadsheet.merge('J8:K8');
spreadsheet.merge('H10:H20');
};
const getMergeRange = () => {
let firstColumn, lastColumn, firstRow, lastRow, cell;
// Get the active sheet.
let sheet = spreadsheet.getActiveSheet();
// Fetch the used range from the active sheet.
let usedRange = sheet.usedRange;
// Loop to iterate between the rows.
for (let i = 0; i <= usedRange.rowIndex; i++) {
// Loop to iterate between the columns.
for (let j = 0; j <= usedRange.colIndex; j++) {
// Condition to check whether the row is present and fetch the cell object.
if (sheet.rows[i]) {
cell = sheet.rows[i].cells[j];
}
// Condition to check whether the cell, rowspan (or) colspan are present and it is merged or not.
if (
(cell && cell.rowSpan && cell.rowSpan > 0) ||
(cell && cell.colSpan && cell.colSpan > 0)
) {
// Fetch index of the start column header text.
firstColumn = getColumnHeaderText(j + 1);
// Fetch index of the end column header text.
lastColumn = cell.colSpan
? getColumnHeaderText(j + cell.colSpan)
: getColumnHeaderText(j + 1);
// Fetch index of the start row header value.
firstRow = i + 1;
// Fetch index of the end row header value.
lastRow = cell.rowSpan ? i + cell.rowSpan : i + 1;
// Construct the address range of the merged cells from the collection.
let address = firstColumn + firstRow + ':' + lastColumn + lastRow;
// Log the constructed address to the console.
console.log('Merged Range : ', address);
}
}
}
};
return (
<div>
<SpreadsheetComponent
ref={(ssObj) => {
spreadsheet = ssObj;
}}
created={onCreated}
></SpreadsheetComponent>
<button className="e-btn" onClick={getMergeRange}>
Get Merged Range
</button>
</div>
);
}
export default App;
const root = createRoot(document.getElementById('sample'));
root.render(<App />);
Sample Link:
https://stackblitz.com/edit/react-uzt9lc-gnsakh?file=index.js
Output:
For more details, please refer the following reference.
https://ej2.syncfusion.com/react/documentation/spreadsheet/cell-range#merge-cells