Android (Java/Kotlin) Google Sheets API: Add New Sheet

April 29, 2019
fun addNewSheet(service: Sheets, spreadsheetId: String, name: String): Int? {
    val requests = listOf<Request>(
        // https://developers.google.com/sheets/api/samples/sheet
        Request().setAddSheet(AddSheetRequest().apply {
            properties = SheetProperties().apply {
                title = name
            }
        })
    )

    val body = BatchUpdateSpreadsheetRequest()
        .setRequests(requests)

    val result = service.spreadsheets().batchUpdate(spreadsheetId, body).execute()
    var sheetId: Int? = null
    val spreadsheet = result.updatedSpreadsheet
    for (reply in result.replies) {
       sheetId = reply.addSheet.properties.sheetId
    }

    return sheetId
}

NOTE: service is Sheets. Refer to Get Google Sheets service instance.

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.