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