簡體   English   中英

導出為 XLSX 格式 python google sheet api

[英]EXPORT AS XLSX format python google sheet api

我可以知道我需要做什么才能將 google sheet 中的文件導出為 xlsx 格式嗎?

我下面的代碼正在運行,但我還需要將文件保存為 xlsx 格式...... :(

這是我的代碼:

from oauth2client.service_account import ServiceAccountCredentials
import gsheets

pdkey = "keypd.json"
url = f"https://docs.google.com/spreadsheets/d/1MCkqb_123123123123asdasdada/edit#gid=0"

SCOPE = ["https://spreadsheets.google.com/feeds", 'https://www.googleapis.com/auth/spreadsheets',
         "https://www.googleapis.com/auth/drive.file", "https://www.googleapis.com/auth/drive"]
CREDS = ServiceAccountCredentials.from_json_keyfile_name(pdkey, SCOPE)

sheets = gsheets.Sheets(CREDS)
sheet = sheets.get(url)
sheet[0].to_csv("/root/xlsx/SAMPLE.csv")

在你的情況下,用Drive API的導出方式導出Spreadsheet怎么樣? 當這反映在您的腳本中時,它將變為如下所示。

修改后的腳本:

從:

sheets = gsheets.Sheets(CREDS)
sheet = sheets.get(url)
sheet[0].to_csv("/root/xlsx/SAMPLE.csv")

到:

access_token = CREDS.create_delegated(CREDS._service_account_email).get_access_token().access_token
url = "https://www.googleapis.com/drive/v3/files/" + spreadsheet_id + "/export?mimeType=application%2Fvnd.openxmlformats-officedocument.spreadsheetml.sheet"
res = requests.get(url, headers={"Authorization": "Bearer " + access_token})

# If you want to create the XLSX data as a file, you can use the following script.
with open("sample.xlsx", 'wb') as f:
    f.write(res.content)
  • 在此腳本中,請添加import requests
  • 在這個修改后的腳本中,使用 Drive API 中的導出方法將電子表格導出為 XLSX 數據。 訪問令牌是從服務帳戶中檢索的。

參考:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM