Home > Backend Development > Golang > How to Write/Update Data in Google Sheets API V4 with Go?

How to Write/Update Data in Google Sheets API V4 with Go?

Patricia Arquette
Release: 2024-11-05 22:48:02
Original
675 people have browsed it

How to Write/Update Data in Google Sheets API V4 with Go?

How to Write/Update Data in Google Sheets API V4 Using Go?

Problem:

Despite reviewing the quick start guide, writing data to Google Sheets using the Go library proves challenging. The complexity of the library poses a hurdle, and there is a lack of available examples.

Solution:

After experimenting, the following code snippet provides a solution:

<code class="go">func write() {
    // Load client secret file
    b, err := ioutil.ReadFile("./Google_Sheets_API_Quickstart/client_secret.json")
    if err != nil {
        log.Fatalf("Unable to read client secret file: %v", err)
    }

    // Configure the client
    config, err := google.ConfigFromJSON(b, "https://www.googleapis.com/auth/spreadsheets")
    if err != nil {
        log.Fatalf("Unable to parse client secret file to config: %v", err)
    }
    client := getClient(ctx, config)

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

    // Set spreadsheet and range variables
    spreadsheetId := "YOUR SPREADSHEET ID"
    writeRange := "A1"

    // Create ValueRange object
    var vr sheets.ValueRange

    // Add values to the range
    myval := []interface{}{"One", "Two", "Three"}
    vr.Values = append(vr.Values, myval)

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

This code reads the client secret JSON file, configures the client, creates a Sheets client, sets the spreadsheet and range, creates the ValueRange object, adds values to the range, and updates the spreadsheet.

The above is the detailed content of How to Write/Update Data in Google Sheets API V4 with Go?. 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