Search code examples
javagoogle-sheetsgoogle-drive-apigoogle-sheets-apigoogle-client

How do I get sorted cell data from the Google sheets v4 API?


In the v3 API I could do something like:

String listFeedUrl = (new URI(worksheet.getListFeedUrl().toString())).toURL();
ListQuery lq = new ListQuery(listFeedUrl);

lq.setOrderBy("column:name");
lq.setReverse(false);

ListFeed lf = spreadsheetService.query(lq, ListFeed.class);

In v4 I'm not seeing an equivalent. What is the recommended way to get sorted cell data? Is my only choice to sort it once it's returned?


Solution

  • In fact you can do this, but the idea is to execute a request on the sheet to explicitly order the columns. I've managed to do it like this :

    BatchUpdateSpreadsheetRequest busReq = new BatchUpdateSpreadsheetRequest();
    SortSpec ss = new SortSpec();
    // ordering ASCENDING or DESCENDING
    ss.setSortOrder("DESCENDING");
    // the column number starting from 0
    ss.setDimensionIndex(1);
    SortRangeRequest srr = new SortRangeRequest();
    srr.setSortSpecs(Arrays.asList(ss));
    Request req = new Request();
    req.setSortRange(srr);
    busReq.setRequests(Arrays.asList(req));
    // mService is a instance of com.google.api.services.sheets.v4.Sheets
    this.mService.spreadsheets().batchUpdate(spreadsheetId, busReq).execute();