1

I am trying to implement the Google sheets API writing feature into my app using following code from this web page but unable to figure out what and how to assign a value to a ValueRange variable.

public class SheetsExample {
public static void main(String args[]) throws IOException,
GeneralSecurityException {
// The ID of the spreadsheet to update.
String spreadsheetId = "my-spreadsheet-id"; // TODO: Update placeholder value.

//The A1 notation of the values to update.
String range = "my-range"; // TODO: Update placeholder value.

// TODO: Assign values to desired fields of `requestBody`. All existing
// fields will be replaced:
ValueRange requestBody = new ValueRange();

Sheets sheetsService = createSheetsService();
Sheets.Spreadsheets.Values.Update request =
    sheetsService.spreadsheets().values().update(spreadsheetId, range, requestBody);

UpdateValuesResponse response = request.execute();

// TODO: Change code below to process the `response` object:
System.out.println(response);
  }



 public static Sheets createSheetsService() throws IOException, GeneralSecurityException {
    HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();

// TODO: Change placeholder below to generate authentication credentials. See
// https://developers.google.com/sheets/quickstart/java#step_3_set_up_the_sample
//
// Authorize using one of the following scopes:
//   "https://www.googleapis.com/auth/drive"
//   "https://www.googleapis.com/auth/drive.file"
//   "https://www.googleapis.com/auth/spreadsheets"
GoogleCredential credential = null;

return new Sheets.Builder(httpTransport, jsonFactory, credential)
    .setApplicationName("Google-SheetsSample/0.1")
    .build();
}  
}
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Suyash Doneria
  • 111
  • 2
  • 8
  • what exactly is the problem? you can try actually assigning it: =, or you can changing it's state (use setters), .. – Stultuske Sep 12 '17 at 08:05

3 Answers3

3

Refer the API Guide Google Sheets API v4

First, You need to create a ValueRange instance. You can do this by ValueRange.setValues() method. As @Ben has shown in his answer, you can create the ValueRange instance in the following way. https://stackoverflow.com/a/46171564/2999358

ValueRange requestBody = new ValueRange(); 
requestBody.setValues(
    Arrays.asList(
      Arrays.asList("Row 1 Cell 1", "Row 1 Cell 2", "Row 1 Cell 3"),
      Arrays.asList("Row 2 Cell 1", "Row 2 Cell 2", "Row 2 Cell 3")));

As you can see in the API Guide, setValues() requires an array of arrays

public ValueRange setValues(java.util.List<java.util.List<java.lang.Object>> 
values)

The outer List represents all the data (basically the whole spreadsheet), while the inner Lists represents ROWS. Each item in these Lists represents a CELL.

After you set the values you want to write to your spreadsheet, you can use the ValueRange object (in your case requestBody variable) to update the spreadsheet.

If you have followed https://developers.google.com/sheets/api/quickstart/android quick start guide, do the following changes to that code. Since that code only shows you how to fetch data from a spreadsheet.

Change the following line,

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

to this,

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

This will enable you to view and manage your spreadsheets in Google Drive.

And inside the getDataFromAPI() method in this guide, contains following code,

ValueRange response = this.mService.spreadsheets().values()
                .get(spreadsheetId, range)
                .execute();

which is used to fetch data from the spreadsheet. Change this to following,

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

Setting ValueInputOption to "RAW" will make the values you enter to be stored as-is. If you use "USER_ENTERED", the values you enter will be parsed as you are entering a value to a cell from the Google Spreadsheet UI. Which will do conversions like strings to Numbers, Dates etc. Basically all the rules that will apply when you use the Google spreadsheet UI. This is up-to you how you want to handle.

k9yosh
  • 858
  • 1
  • 11
  • 31
  • Can you be so kind and tell me how to convert this code developers.google.com/sheets/api/quickstart/android for read function to append or write function .Thanks in Advance – Suyash Doneria Sep 12 '17 at 13:43
  • @SuyashDoneria look at the getDataFromApi(). You can use this to fetch data from the spreadsheet. This is a complete example on fetching data from a google spreadsheet. I'm not familiar with Google Spreadsheet, but here's an answer that might help you. https://stackoverflow.com/questions/38052635/how-to-update-write-data-to-google-spreadsheet-api-android-api-v4 – k9yosh Sep 13 '17 at 04:32
  • @SuyashDoneria If my answer helped your initial question, please mark it as the correct answer. – k9yosh Sep 13 '17 at 04:34
  • Thanks a lot and thank you for the prompt reply but i can't understand how to add a new row with values eg.food,cars,coffee, engine , how would i do that? Thanks in Advance! – Suyash Doneria Sep 13 '17 at 10:34
  • @SuyashDoneria Now only i understood what you are trying to do. You must create a ValueRange instance of your own. Use the setValues() method to set the values you want to write. setValues accepts a list of lists. So the outer list (List) denotes ROWS, while objects of inner lists denotes ROWS. As Ben has mentioned above, you can set the values. And the link i sent u contains the update method, which will take this ValueRange instance, and write the values to the corresponding Spreadsheet. I will update this answer. – k9yosh Sep 13 '17 at 11:02
  • 1
    hanks for such an elaborative answer, but I am getting an error when I am executing this line of `ValueRange requestBody=newValueRange(); requestBody.setValues(Arrays.asList( Arrays.asList("Row 1 Cell 1", "Row 1 Cell 2", "Row 1 Cell 3"), Arrays.asList("Row 2 Cell 1", "Row 2 Cell 2", "Row 2 Cell 3")));` that List> cannot be converted to List> ValueRange cannot be converted to List> Thanks in Advance!! – Suyash Doneria Sep 13 '17 at 14:12
  • @SuyashDoneria I executed the same code, and there is no error. If you copy pasted the same code you executed, then your code has an issue. `new` keyword should be separated from `ValueRange()`. Please check, the code should run without an issue. – k9yosh Sep 13 '17 at 15:12
  • @SuyashDoneria it's the same code. I copy pasted the one you sent. – k9yosh Sep 13 '17 at 15:47
  • Just to be sure where did you paste it in the code? This is my error https://drive.google.com/file/d/0B6c-uEbxxR2ZNUV3MEVNc2RXd00/view?usp=sharing – Suyash Doneria Sep 13 '17 at 16:02
  • @SuyashDoneria Restart your IDE, Refresh your project – k9yosh Sep 13 '17 at 16:03
  • @SuyashDoneria If it doesn't work, ignore and try rebuilding the project. Android Studio is known for these kind of bugs. – k9yosh Sep 13 '17 at 16:06
  • Tried that, so please just to be sure can you share your code, I would be extremely grateful to you – Suyash Doneria Sep 13 '17 at 16:53
  • Thanks for the great support with your answers and Ashwiinn Karaangutkar's answer to https://stackoverflow.com/questions/38107237/write-data-to-google-sheet-using-google-sheet-api-v4-java-sample-code , I was finally able to execute the code , so thank you so much – Suyash Doneria Sep 13 '17 at 19:34
1

I think what you are actually trying to do here is update an existing range with a set of values?

In that case you can do that like this :

   ValueRange requestBody = new ValueRange(); 
   requestBody.setValues(
        Arrays.asList(
          Arrays.asList("Row 1 Cell 1", "Row 1 Cell 2", "Row 1 Cell 3"),
          Arrays.asList("Row 2 Cell 1", "Row 2 Cell 2", "Row 2 Cell 3")));

Hope that helps, in practice you would build up your lists programatically.

Ben
  • 532
  • 2
  • 4
  • 12
  • Can you be so kind and tell me how to convert this code https://developers.google.com/sheets/api/quickstart/android for read function to append or write function – Suyash Doneria Sep 12 '17 at 10:47
0

I leave my contribution with a concrete example that does not throw compilation errors in the answer:

https://stackoverflow.com/a/48832281/1621848

Thanks.

Diego Soto
  • 375
  • 3
  • 8