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') '''
我相信你的目标和情况如下。
pd.read_excel
。gauth = GoogleAuth()
可用于下载 XLSX 格式的 Google 电子表格。在这种情况下,我想提出以下流程。
requests
库将电子表格导出为 XLSX 格式。gauth = GoogleAuth()
。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)
归档时间: |
|
查看次数: |
15215 次 |
最近记录: |