从谷歌驱动器读取Excel文件而不下载文件

ann*_*yos 3 python excel google-drive-api

我想从 Google Drive 上的Excel 文件读取 Excel 工作表,而无需在本地计算机上下载!我搜索了 google Drive api 但找不到解决方案我尝试了以下代码请需要建议:

'''
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
import pandas as pd

gauth = GoogleAuth()
gauth.LocalWebserverAuth()
drive = GoogleDrive(gauth)

file_id = 'abc'
file_name = 'abc.xlsx'  

downloaded = drive.CreateFile({'id': file_id})
downloaded.GetContentFile(file_name)


class TestCase:
  def __init__(self, file_name, sheet):
    self.file_name = file_name
    self.sheet = sheet
    testcase = pd.read_excel(file_name, usecols=None, sheet_name=sheet)
    print(testcase)


class TestCaseSteps:
   def __init__(self, file_name, sheet):
    self.file_name = file_name
    self.sheet = sheet
    testcase = pd.read_excel(file_name, usecols=None, sheet_name=sheet)
    print(testcase)
Run Code Online (Sandbox Code Playgroud)

测试用例 = TestCase(file_name, 'A') 步骤 = TestCaseSteps(file_name, 'B') '''

Tan*_*ike 5

我相信你的目标和情况如下。

  • 您想使用 阅读从 Google Drive 下载的 XLSX pd.read_excel
  • 您希望在不将下载的 XLSX 数据保存为文件的情况下实现此目的。
  • gauth = GoogleAuth()可用于下载 XLSX 格式的 Google 电子表格。

在这种情况下,我想提出以下流程。

  1. 下载 XLSX 格式的 Google 电子表格。
    • 在这种情况下,它直接请求端点使用requests库将电子表格导出为 XLSX 格式。
    • 访问令牌是从 检索的gauth = GoogleAuth()
  2. 下载的 XLSX 数据用 读取pd.read_excel
    • 在本例中,BytesIO用于读取数据。

通过该流程,当将电子表格作为XLSX数据下载时,可以读取XLSX数据而不将其保存为文件。当上述流程反映到脚本中时,就会变成如下所示。

示例脚本:

在运行脚本之前,请设置电子表格 ID。

from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
import pandas as pd
import requests
from io import BytesIO

spreadsheetId = "###"  # <--- Please set the Spreadsheet ID.

# 1. Download the Google Spreadsheet as XLSX format.
gauth = GoogleAuth()
gauth.LocalWebserverAuth()
url = "https://www.googleapis.com/drive/v3/files/" + spreadsheetId + "/export?mimeType=application%2Fvnd.openxmlformats-officedocument.spreadsheetml.sheet"
res = requests.get(url, headers={"Authorization": "Bearer " + gauth.attr['credentials'].access_token})

# 2. The downloaded XLSX data is read with `pd.read_excel`.
sheet = "Sheet1"
values = pd.read_excel(BytesIO(res.content), usecols=None, sheet_name=sheet)
print(values)
Run Code Online (Sandbox Code Playgroud)

参考:

添加:

在以下示例脚本中,假设将 XLSX 文件放入 Google Drive,并下载 XLSX 文件。

from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
import pandas as pd
import requests
from io import BytesIO

file_id = "###"  # <--- Please set the file ID of XLSX file.

# 1. Download the XLSX data.
gauth = GoogleAuth()
gauth.LocalWebserverAuth()
url = "https://www.googleapis.com/drive/v3/files/" + file_id + "?alt=media"
res = requests.get(url, headers={"Authorization": "Bearer " + gauth.attr['credentials'].access_token})

# 2. The downloaded XLSX data is read with `pd.read_excel`.
sheet = "Sheet1"
values = pd.read_excel(BytesIO(res.content), usecols=None, sheet_name=sheet)
print(values)
Run Code Online (Sandbox Code Playgroud)