Android (Java/Kotlin) Google Sheets API: Get Sheet Name or Id

April 7, 2019
val service = ...
val spreadsheetId = ...
val findSheetName = 'Sheet1'

val spreadsheet = service.spreadsheets().get(spreadsheetId).execute()
/*
for (sheet in spreadsheet.sheets) {
    Timber.d("sheetId=${sheet.properties.sheetId}, title=${sheet.properties.title}")
}
 */

val sheet = if (spreadsheet.sheets.size == 1) {
    spreadsheet.sheets[0]
}
else {
    var defaultSheet: Sheet? = null
    var findSheet: Sheet? = null
    for (sheet in spreadsheet.sheets) {
        if (sheet.properties.sheetId == 0) {
            defaultSheet = sheet
        }
        else if (sheet.properties.title == findSheetName) {
            findSheet = sheet
        }
    }

    findSheet ?: defaultSheet!!
}

val sheetName = sheet.properties.title
val sheetId = sheet.properties.sheetId

NOTE: The default/first sheet created (e.g. ‘Sheet1’) have an Id of 0.

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