【问题标题】:Google Drive Ruby API won't return spreadsheet contents as csvGoogle Drive Ruby API 不会将电子表格内容返回为 csv
【发布时间】:2016-01-08 22:39:07
【问题描述】:

我正在尝试编写一个 Ruby 脚本来自动从 Google Drive 下载 csv 格式的电子表格。结果文件始终为空。

有趣的是,如果我以 .xlsx 格式下载它,我会得到一个几乎可以使用的文件。 (Excel 会打开文件,但必须先修复它。)

有人看到我的代码中有错误吗? (下面的代码是谷歌提供的'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')

【问题讨论】:

    标签: ruby google-sheets google-drive-api


    【解决方案1】:

    我不确定您正在使用的库,但根据他们文档中的示例,file resource 应该包含 exportLinks 和相应的

    download_url = file['exportLinks']['application/pdf']
    

    希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-16
      • 1970-01-01
      • 2012-07-22
      • 2012-12-16
      相关资源
      最近更新 更多