我正在使用ruby客户端使用Google :: Apis :: SheetsV4 :: SheetsService类更新现有的电子表格范围,但无法找到创建新工作表的方法。我想为每个新的一年创建一个新表。我想通过标题测试电子表格中是否存在工作表,如果不存在则添加新工作表。我找不到任何帮助我完成任务的ruby代码示例。
这不能与作为重复问题提出的链接重复,因为我在下面的回答中的ruby代码与用C#编写的解决方案非常不同。
http://www.rubydoc.info/github/google/google-api-ruby-client/Google/Apis/SheetsV4/SheetsService
以下是我的一些代码:
require 'google/apis/sheets_v4'
SCOPE = Google::Apis::SheetsV4::AUTH_SPREADSHEETS
spreadsheet_id = '1NTvP-VkDDE1_xzz_etc'
答案 0 :(得分:5)
好的,这里的答案是我认为与建议的副本有很多不同的代码,应删除哪些引用。此代码包括用于查询工作表属性和更新值以及将新列附加到工作表的方法。
此答案应与https://developers.google.com/drive/v3/web/quickstart/ruby
一起阅读公共代码:
service = Google::Apis::SheetsV4::SheetsService.new
service.client_options.application_name = APPLICATION_NAME
service.authorization = authorize
添加新表:
sheet_name = '2020'
column_count = 55
add_sheet_request = Google::Apis::SheetsV4::AddSheetRequest.new
add_sheet_request.properties = Google::Apis::SheetsV4::SheetProperties.new
add_sheet_request.properties.title = sheet_name
grid_properties = Google::Apis::SheetsV4::GridProperties.new
grid_properties.column_count = column_count
add_sheet_request.properties.grid_properties = grid_properties
batch_update_spreadsheet_request = Google::Apis::SheetsV4::BatchUpdateSpreadsheetRequest.new
batch_update_spreadsheet_request.requests = Google::Apis::SheetsV4::Request.new
batch_update_spreadsheet_request_object = [ add_sheet: add_sheet_request ]
batch_update_spreadsheet_request.requests = batch_update_spreadsheet_request_object
response = service.batch_update_spreadsheet(spreadsheet_id,
batch_update_spreadsheet_request)
puts ">>>>>>>>>> response: #{response.inspect}"
更新电子表格值:
range = 'Sheet1!A1:C2'
value_range_object = {
"major_dimension": "ROWS",
"values": [
["Multiplicand", "Multiplier", "Result"],
["2", "8", "=A2*B2"]
]
}
response = service.clear_values(spreadsheet_id, "Sheet1!A1:Z99")
response = service.update_spreadsheet_value(spreadsheet_id, range,
value_range_object, value_input_option: 'USER_ENTERED')
获取电子表格的属性,标题和列数:
response = service.get_spreadsheet(spreadsheet_id)
puts ">>>>>>>>>> response: #{response.inspect}"
response.sheets.each do |s|
puts s.properties.sheet_id
puts s.properties.index
puts s.properties.title
puts s.properties.grid_properties.column_count
end
将新列附加到工作表:
append_dimension_request = Google::Apis::SheetsV4::AppendDimensionRequest.new
append_dimension_request.dimension = 'COLUMNS'
append_dimension_request.length = 30
append_dimension_request.sheet_id = 1491311133
batch_update_spreadsheet_request = Google::Apis::SheetsV4::BatchUpdateSpreadsheetRequest.new
batch_update_spreadsheet_request.requests = Google::Apis::SheetsV4::Request.new
batch_update_spreadsheet_request_object = [ append_dimension: append_dimension_request ]
batch_update_spreadsheet_request.requests = batch_update_spreadsheet_request_object
response = service.batch_update_spreadsheet(spreadsheet_id, batch_update_spreadsheet_request)