Home > Backend Development > Golang > How to Write and Update Google Sheets Data with Go (API V4)?

How to Write and Update Google Sheets Data with Go (API V4)?

Mary-Kate Olsen
Release: 2024-11-06 20:58:03
Original
768 people have browsed it

How to Write and Update Google Sheets Data with Go (API V4)?

Writing and Updating Google Sheets Data with Go (API V4)

When attempting to write data to a Google Sheet using the Golang library, the absence of clear examples can be frustrating. Here's a straightforward solution, using a modified version of the main function from the official quick start guide:

<code class="go">func write() {
    // Required OAuth2 setup (see quick start guide for details)

    srv, err := sheets.New(client)
    if err != nil {
        log.Fatalf("Unable to retrieve Sheets Client %v", err)
    }

    spreadsheetId := "YOUR_SPREADSHEET_ID"
    writeRange := "A1"
    var vr sheets.ValueRange

    // Example data to be written (here: three columns)
    myval := []interface{}{"One", "Two", "Three"}
    vr.Values = append(vr.Values, myval)

    _, err = srv.Spreadsheets.Values.Update(spreadsheetId, writeRange, &vr).ValueInputOption("RAW").Do()
    if err != nil {
        log.Fatalf("Unable to update sheet data %v", err)
    }
}</code>
Copy after login

In this modified main function:

  • OAuth2 setup is still necessary (see the quick start guide).
  • Create a sheets service with srv, err := sheets.New(client).
  • Define the spreadsheetId and writeRange (e.g., "A1").
  • Create a ValueRange struct (vr) to hold the data.
  • Populate vr.Values with your desired data (e.g., myval).
  • Use ValueInputOption("RAW") to specify raw values.
  • Finally, execute the Update request, providing the spreadsheet ID, write range, and value range.

The above is the detailed content of How to Write and Update Google Sheets Data with Go (API V4)?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template