[英]Google Sheets API V4 Add Row .NET
Google文檔頁面說
Sheets API v4確實提供了一個AppendCells請求,該請求可以與電子表格.batchUpdate方法一起使用,以將數據行追加到表單(並根據需要同時更新單元格屬性和格式)。
即使創建RowData有效負載很繁瑣,這也確實可以添加新行。 但是,這不允許設置ValueInputOption。
谷歌還說
但是,通常更簡單的方法是簡單地確定要添加的行的A1表示法,然后發出sheets.values.update請求以覆蓋該行。 在這種情況下,指定行中的任何數據都會被覆蓋。
現在,這適用於更新現有行上的數據-包括ValueInputOption。 但是,當我使用它來追加新行(即提供下一行的范圍)時,服務器返回503錯誤。 我一定有一個竅門嗎?
正如評論者所建議的,我應該在問題中張貼代碼。 但是,我將其發布為此答案的一部分-這顯然是次優的解決方案,但符合我的目的。
這是我最終得到的代碼(省略了OAuth和服務實例化)
Public Function AddRows(Values As Object()()) As Boolean
Try
'Create dummy rows value payload
Dim cell2add As New CellData
Dim cellval As New ExtendedValue
cellval.NumberValue = 0
cell2add.UserEnteredValue = cellval
Dim data2add As New RowData
data2add.Values = {cell2add}
Dim rowdataList As New List(Of RowData)
For i = 0 To UBound(Values)
rowdataList.Add(data2add)
Next
'Add a request to append to the sheet's data (expand grid)
Dim appendRequest As New AppendCellsRequest
appendRequest.SheetId = SheetID
appendRequest.Rows = rowdataList.ToArray
appendRequest.Fields = "*"
Dim request As New Request
request.AppendCells = appendRequest
'Execute the request
Dim bRequest As New BatchUpdateSpreadsheetRequest
bRequest.Requests = {request}
Dim bResponse As BatchUpdateSpreadsheetResponse = Service.Spreadsheets.BatchUpdate(bRequest, DataBaseName).Execute()
'Now update the newly added rows with data
Dim index As Integer = GetRowCount() - Values.Length + 2 'GetRowCount() calls the service to get sheet metadata and returns the rows of data (excluding the headers)
Dim vals As New ValueRange
vals.Values = Values
Dim urequest As SpreadsheetsResource.ValuesResource.UpdateRequest =
Service.Spreadsheets.Values.Update(vals, DataBaseName, Name & "!A" & index)
urequest.ValueInputOption = SpreadsheetsResource.ValuesResource.UpdateRequest.ValueInputOptionEnum.USERENTERED
Dim response As UpdateValuesResponse = urequest.Execute
Return response.UpdatedRows = Values.Length
Catch ex As Exception
Trace.WriteLine(Now.ToLongTimeString & ":" & ex.Message)
Return False
End Try
End Function
簡而言之,我正在調用AppendCells來擴展“網格”的大小,然后更新由此創建的空白行中的值。 如果您嘗試更新新行的值,則服務器將返回“服務不可用”錯誤。 我嘗試更新現有行中的值(values.batchUpdate)並在同一請求中添加新行時發現了問題。 在這種情況下,錯誤消息提到“超出網格”更新。
沒有用於通過電子表格.values集合(支持A1表示法和ValueInputOption的集合)追加行的API。 我們正在內部跟蹤該功能請求,並可能會增加支持。 同時,添加行的唯一方法是通過batchUpdate方法(盡管,如果您不需要CellData對象提供的額外功能(例如格式化),那么按照您所說的那樣繁瑣)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.