Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to group rows or columns in Excel using Office JS API

I am converting a VSTO Excel add-in to a Web Excel add-in (using JavaScript API for Office). In my VSTO C# code I have the following line:

worksheet.Rows[rowStart + ":" + rowEnd].Group()

and a similar line for columns:

worksheet.Columns[colStart + ":" + colEnd].Group();

What is the equivalent API call for Office-JS? Could not find a relevant entry in the API Docs

like image 768
July.Tech Avatar asked Oct 29 '25 00:10

July.Tech


2 Answers

I'm afraid that that kind of grouping is not yet supported in office.js. Please vote up the suggestion in the Office Developer Suggestion box: Grouping and ungrouping rows and columns.

like image 121
Rick Kirkham Avatar answered Oct 31 '25 18:10

Rick Kirkham


See --> https://learn.microsoft.com/en-us/office/dev/add-ins/excel/excel-add-ins-ranges-group

https://learn.microsoft.com/en-us/javascript/api/excel/excel.range?view=excel-js-preview#excel-excel-range-group-member(1)

Here is how I did it. First thing I noticed was that I wanted certain groups to be collapsed by default. I accomplished this w/ hidden = true which combined w/ grouping, its more of a hide by default.

const Rng_Group_Obj = {
    "group": {
        "groupOptionString": {
            "ByRows": "ByRows",
            "ByColumns": "ByColumns",
        },
    },
    "columnHidden": true,
    "rowHidden": true,
}

function Do_Group_Rng(rng, ByColumns, ByRows, Opt_Hidden_By_Default) {
    if (ByColumns == true) {
        rng.group(Rng_Group_Obj.group.groupOptionString.ByColumns)
        if (Opt_Hidden_By_Default == true) { rng.columnHidden = Rng_Group_Obj.columnHidden }
    }
    if (ByRows == true) {
        rng.group(Rng_Group_Obj.group.groupOptionString.ByRows)
        if (Opt_Hidden_By_Default == true) { rng.rowHidden = Rng_Group_Obj.rowHidden }
    }
    return true;
}

var ws = context.workbook.worksheets.getActiveWorksheet()

var rng = ws.getRange("G:K")
Do_Group_Rng(rng,true,false,true)

var rng = ws.getRange("4:7")
Do_Group_Rng(rng, false, true, true)
like image 32
FreeSoftwareServers Avatar answered Oct 31 '25 18:10

FreeSoftwareServers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!