我正在尝试编写一个Ruby脚本,以csv格式从Google Drive自动下载电子表格。生成的文件始终为空。
有趣的是,如果我以.xlsx格式下载它,我会得到一个几乎可以工作的文件。 (Excel将打开该文件,但必须先修复它。)
有人看到我的代码中有错误吗? (下面的代码是Google提供的" quickstart.rb'示例代码,最后进行了一些修改。)
require 'google/apis/drive_v3'
require 'googleauth'
require 'googleauth/stores/file_token_store'
require 'fileutils'
OOB_URI = 'urn:ietf:wg:oauth:2.0:oob'
APPLICATION_NAME = 'Drive API Ruby Quickstart'
CLIENT_SECRETS_PATH = 'client_secret.json'
CREDENTIALS_PATH = File.join(Dir.home, '.credentials',
"drive-ruby-quickstart.yaml")
SCOPE = Google::Apis::DriveV3::AUTH_DRIVE
##
# Ensure valid credentials, either by restoring from the saved credentials
# files or intitiating an OAuth2 authorization. If authorization is required,
# the user's default browser will be launched to approve the request.
#
# @return [Google::Auth::UserRefreshCredentials] OAuth2 credentials
def authorize
FileUtils.mkdir_p(File.dirname(CREDENTIALS_PATH))
client_id = Google::Auth::ClientId.from_file(CLIENT_SECRETS_PATH)
token_store = Google::Auth::Stores::FileTokenStore.new(file: CREDENTIALS_PATH)
authorizer = Google::Auth::UserAuthorizer.new(
client_id, SCOPE, token_store)
user_id = 'default'
credentials = authorizer.get_credentials(user_id)
if credentials.nil?
url = authorizer.get_authorization_url(
base_url: OOB_URI)
puts "Open the following URL in the browser and enter the " +
"resulting code after authorization"
puts url
code = gets
credentials = authorizer.get_and_store_credentials_from_code(
user_id: user_id, code: code, base_url: OOB_URI)
end
credentials
end
# Initialize the API
service = Google::Apis::DriveV3::DriveService.new
service.client_options.application_name = APPLICATION_NAME
service.authorization = authorize
response = service.list_files(page_size: 1000, fields: 'nextPageToken, files(id, name)')
budget_sheet = response.files.find {|file| file.name == 'Budget 2012'}
# Make sure the file is found
puts "#{budget_sheet.name} (#{budget_sheet.id})"
# This almost works. (File foo.xlsx contains data, but Excel complains that it has errors)
service.export_file(budget_sheet.id, 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', download_dest: '/tmp/foo.xlsx')
# This does not work. It always generates an empty file
service.export_file(budget_sheet.id, 'text/csv', download_dest: '/tmp/foo.csv')
答案 0 :(得分:0)
我不确定您使用的库,但根据其文档中的示例,file resource应包含exportLinks
及相应的
download_url = file['exportLinks']['application/pdf']
希望这有帮助!