1

I have a 3 column Spreadsheet [Date, Time, Subject] that I want to populate via the Sheets API using Java.

I understand how to read rows:

    for (List row : values)
        System.out.println(row.get(0) + row.get(1) + row.get(2));

But I am having trouble using their documentation to understand how to insert specific strings into specific rows and columns. I know there exists a method row.set(int index, Object element) but when I try to insert a new row like this:

    for (List row : values)
    {
        row.set(0, message.full_date);
        row.set(1, message.time);
        row.set(2, message.subject);
    }

nothing is updating in my sheets. My full code:

private static void Update_Sheets(Sheets sheets_service, GmailMessage message) throws IOException
    {
        String spreadsheetId = id;

        String range = "Sheet1!A1:C2";
        ValueRange response = sheets_service.spreadsheets().values()
                .get(spreadsheetId, range)
                .execute();
        List<List<Object>> values = response.getValues();

        for (List row : values)
        {
            row.set(0, message.full_date); //a string
            row.set(1, message.time);      //a string
            row.set(2, message.subject);   //a string
        }
    }
Rubén
  • 34,714
  • 9
  • 70
  • 166
  • Did you receive any kind of errors? Also, try to check this [documentation](https://developers.google.com/sheets/guides/values#writing_multiple_ranges) about writing multiple discontinuous ranges. – KENdi Sep 12 '16 at 00:25

1 Answers1

0

Here is a question similar to yours, already asked in the stacks forums Write data to Google Sheet using Google Sheet API V4 - Java Sample Code

I used @"Ashwin Karangutkar" solution and worked for me fine.

This answer also breaks it down well: Write data into Google Spreadsheet w/ Java from @"Zsolt Balla"

Things to take into consideration

1) You have to delete the /.credentials\sheets.googleapis.com-java-quickstart file, because unlike the google spreadsheet quickstart, which gives you only the read permissions, you need the write permissions also to edit the spreadsheet.

2) This is the line that determines read/write permissions private static final List SCOPES = Arrays.asList(SheetsScopes.SPREADSHEETS);

3) the only thing you need to change is String spreadsheetId = "1234"; with your own spreadsheet id. Mess around with the code, you should be able to figure it out, it should be trivial.

Regards,

Nikos.

Community
  • 1
  • 1
Nick Ko
  • 435
  • 4
  • 16