How to write to Google Sheets in Swift

假如想象 提交于 2021-02-18 06:58:27

问题


I'm trying to write to a Google Sheets document by following this google api, but I'm not having much success. I'm not even sure I'm following the right api, because it says "Appscript" and looks like Swift.

I've been able to read in data from the sheets using:

private let scopes = [kGTLRAuthScopeSheetsSpreadsheets]
private let service = GTLRSheetsService()

override func viewDidLoad() {
    super.viewDidLoad()
    self.service.authorizer = GIDSignIn.sharedInstance().currentUser.authentication.fetcherAuthorizer()
    getData()
}

func getData() {
        let spreadsheetId = "1OAbhzY7RlfCEre-I5e-Kcgz16eHz2cGpO9HZKOiizCs" // Portfolio
    let query = GTLRSheetsQuery_SpreadsheetsValuesGet.query(withSpreadsheetId: spreadsheetId, range:range)
    service.executeQuery(query, delegate: self, didFinish: #selector(displayResultWithTicket(ticket:finishedWithObject:error:)))
}

I tried following the section where the api says:

// This code uses the Sheets Advanced Service, but for most use cases
// the built-in method SpreadsheetApp.getActiveSpreadsheet()
//     .getRange(range).setValues(values) is more appropriate.
var values = [
  [
    // Cell values ...
  ]
  // Additional rows ...
];
var valueRange = Sheets.newValueRange();
valueRange.values = values;
var result = Sheets.Spreadsheets.Values.update(valueRange, spreadsheetId, range, {
  valueInputOption: valueInputOption
});

But I'm very lost in what SpreadsheetsApp.getActiveSpreadsheet() is coming from. I don't really know what the SpreadsheetsApp or Sheets object/library even is, and it doesn't seem to exist when I try to use it in my code

Being utterly lost on how to do this, I tried:

func writeData() {
    let spreadsheetId = "1OAbhzY7RlfCEre-I5e-Kcgz16eHz2cGpO9HZKOiizCs"
    let range = "A1:E"
    let query = GTLRSheetsQuery_SpreadsheetsValuesGet.query(withSpreadsheetId: spreadsheetId, range:range)
    var values = [[]]
    var valueRange = query.newValueRange()
    valueRange.values = values
    var result = query.values.update(valueRange, spreadsheetId, range, {
        valueInputOption: valueInputOption
    })
}

But, as expected, I get a lot of errors since query does not have a newValueRange method, or a values.update method or anything like that.

Can anyone help me please? I'm very lost


回答1:


Here's an answer to your question using the GoogleAPIClientForREST library that you referenced in your original question (not that using AlamoFire is incorrect, but the Google Sheets APIs would be the more canonical way to do it):

func updateSheets() {
    let range = "Sheet1!A3:C3" // Sheet titled "Sheet1", range A3 to C3
    let updateValues = [["Foo", "Bar", "Baz"]]
    let valueRange = GTLRSheets_ValueRange() // GTLRSheets_ValueRange holds the updated values and other params
    valueRange.majorDimension = "ROWS" // Indicates horizontal row insert
    valueRange.range = range
    valueRange.values = updateValues
    let query = GTLRSheetsQuery_SpreadsheetsValuesAppend.query(withObject: valueRange, spreadsheetId: kSpreadsheetID, range: range) // Use an append query to append at the first blank row
    query.valueInputOption = "USER_ENTERED"
    service.executeQuery(query) { ticket, object, error in
        print("object")
    } // `GTLRServiceCompletionHandler` closure containing the service ticket, `GTLRSheets_AppendValuesResponse`, and any error
}



回答2:


I managed to figure it out. So in order to write to google sheets, I needed a JSON PUT request (or POST request), which I sent in using Alamofire. Since I had already configured Google Sign-In previously in my app, all it took was to figure out the syntax and apply the authorization token from my GIDSignIn.sharedInstance().currentUser.authentication.accessToken and use it as a header in the Alamofire JSON request. Here is the code:

import GoogleSignIn
import GoogleAPIClientForREST
import Foundation

import Alamofire

class TestController: UIViewController {

    private let scopes = [kGTLRAuthScopeSheetsSpreadsheets]
    private let service = GTLRSheetsService()

    override func viewDidLoad() {
        super.viewDidLoad()

        let sheetID = "1OAbhzY7RlfCEre-I5e-Kcgz16eHz2cGpO9HZKOiizCs"
        let range = "A3:B4"
        let requestParams = [
            "values": [ 
                ["hi1", "hi2"],
                ["hi3", "hi4"]
                ]
            ]
        let accessToken = GIDSignIn.sharedInstance().currentUser.authentication.accessToken!
        let header = ["Authorization":"Bearer \(accessToken)"]
        let requestURL = "https://sheets.googleapis.com/v4/spreadsheets/\(sheetID)/values/\(range)?valueInputOption=USER_ENTERED"
        let req = Alamofire.request(requestURL, method: .put, parameters: requestParams, encoding: JSONEncoding.default, headers: header)
        req.responseJSON { response in debugPrint(response) }
    }

}


来源:https://stackoverflow.com/questions/51015529/how-to-write-to-google-sheets-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!