Android (Java/Kotlin) Google Sheets API: Update Cell Value

April 7, 2019
Update Cell Value by Row and Col Index
val service = ...
val spreadsheetId = ...
val sheetName = 'Sheet1'

val rows = listOf<ValueRange>(
    ValueRange()
        .setRange("'$sheetName'!A1")
        .setValues(listOf(
            listOf<Any>("Update A1")
        )),
    ValueRange()
        .setRange("'$sheetName'!B2")
        .setValues(listOf(
            listOf<Any>("Updaate B2")
        ))
)

val body = BatchUpdateValuesRequest()
    .setValueInputOption("RAW")
    .setData(rows)
val result = service.spreadsheets().values().batchUpdate(spreadsheetId, body).execute()
Timber.d("updatedRows=${result.totalUpdatedRows}")

Convinient method to update cell using Row and Col index.

class SheetHelper {
    companion object {
        // 0 - A
        // 1 - B
        fun toChar(index: Int): Char {
            return (index + 65).toChar()
        }
    }
}

val sheetName = 'Sheet1'
val rows = mutableListOf<ValueRange>()

fun setCellValue(row: Int, col: Int, value: Any) {
    rows.add(
        ValueRange()
            .setRange("'$sheetName'!${SheetHelper.toChar(col)}$row")
            .setValues(mutableListOf(
                listOf<Any>(value)
            ))
    )
}

NOTE: service is Sheets. Refer to Setup Google Sheets API for Android (Java/Kotlin) to get service/Sheets instance.

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