简体   繁体   中英

How to populate Google Sheets via API in Java

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
        }
    }

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"

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM