How to update/write data to google spreadsheet api

2019-03-20 19:52发布

I have been working on an application where I need to write and update data to a spreadsheet using google spreadsheet api. I have followed the Android Quickstart provided by google Google Sheets API Android Quickstart and was able to retreive data from the google spreadsheet but I am not able to understand how to write data. Please help

3条回答
ゆ 、 Hurt°
2楼-- · 2019-03-20 20:29

After a lot of searching for a concrete example and not finding it, only here I was able to get something that worked for me, with the addition that I put for beginners like me. Thanks to @Veiga

Object a1 = new Object();
a1 = "TEST Row 1 Column A";
Object b1 = new Object();
b1 = "TEST Row 1 Column B";

Object a2 = new Object();
a2 = "TEST Row 2 Column A";
Object b2 = new Object();
b2 = "TEST Row 2 Column B";

ValueRange valueRange = new ValueRange();
valueRange.setValues(
        Arrays.asList(
                Arrays.asList(a1, b1),
                Arrays.asList(a2, b2)));

this.mService.spreadsheets().values().update(spreadsheetId, "A1:B2", valueRange)
        .setValueInputOption("RAW")
        .execute();

I leave this concrete example, because other threads that I saw, throw compilation problems such as "List<String> is not acceptable as List<Object>".

But I thank those collaborators, example @k9yosh in the answer to How to assign a value to a ValueRange variable in java? , because they were also an inspiration for me to develop a concrete solution to this case.

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-03-20 20:34

If you followed the Quickstart tutorial correctly, then it you are few steps from learning how to write data.

In the code provided in the Quickstart tutorial, change the line

private static final String[] SCOPES = { SheetsScopes.SPREADSHEETS_READONLY };

to:

private static final String[] SCOPES = { SheetsScopes.SPREADSHEETS };

This will grant access to write on a spreadsheet.

And instead of something like

ValueRange response = this.mService.spreadsheets().values()
                .get(spreadsheetId, range)
                .execute();
List<List<Object>> values = response.getValues();

you must create your own ValueRange instance, valueRange in this example, and then write:

this.mService.spreadsheets().values().update(spreadsheetId, range, valueRange)
                    .setValueInputOption("RAW")
                    .execute();

Choose the ValueInputOption of your preference.

查看更多
姐就是有狂的资本
4楼-- · 2019-03-20 20:49

Please try going through Manage List-based and Cell-based Feeds to read and modify worksheets and data in Google Sheets.

However, since you're looking for the latest, as indicated in your post's title, and since version 4 of the Google Sheets API is now available, the following references will be very helpful too:

查看更多
登录 后发表回答