How to insert row after the last row with value?

If you use the append feature and set the range to the entire sheet, the API will find the last row and append the new data after it.

This web page explains it.

https://developers.google.com/sheets/api/guides/values#appending_values

Here is some sample code:

String range="Sheet1";
insertData.setValues(rows);
AppendValuesResponse response=service.spreadsheets().values()
.append(spreadsheetId,range,insertData).setValueInputOption("USER_ENTERED")
            .execute();

Note that the response will tell you where it was inserted.


You can use AppendCellsRequest to append a row. The below methods should get you going. I haven't included the getRowDataListForCellStrings method as it is rather application specific.

First create a Request object containing a AppendCellsRequest:

public BatchUpdateSpreadsheetResponse appendWorksheet(String cellValues) throws SpreadsheetException {
    AppendCellsRequest appendRequest = new AppendCellsRequest();
    appendRequest.setSheetId( mSheet.getProperties().getSheetId() );
    appendRequest.setRows( getRowDataListForCellStrings(cellValues) );
    appendRequest.setFields("userEnteredValue");

    Request req = new Request();
    req.setAppendCells( appendRequest );

    return executeBatchRequest(req);
}

Then call batchUpdate on the spreadsheets() interface:

BatchUpdateSpreadsheetResponse executeBatchRequest(Request request) throws SpreadsheetException {
    List<Request> requests = new ArrayList<>();
    requests.add( request );

    BatchUpdateSpreadsheetRequest batchRequest = new BatchUpdateSpreadsheetRequest();
    batchRequest.setRequests( requests );

    try {
          return  mService.spreadsheets().batchUpdate(mSpreadsheet.getSpreadsheetId(), batchRequest).execute();
    } catch (IOException e) {
        throw new SpreadsheetException(e);
    }
}

Unfortunately there doesn't seem to be a way to know which rows were updated. Not does is seem possible to set valueInputOption when appending in this way.


The v4 API has no way to ask "what is the last row with data", as it's a different style of API than the Apps Script API. You can infer the last row yourself by requesting the data and counting the offset from your first requested row to the last returned row.