You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Google Drive API导出Google Sheets的PDF请求添加自定义参数?

问题描述

我拥有一个Google Sheet,希望将其导出为带有如下自定义设置的PDF文件:

size=6.29921x23.2283
portrait=true
fitw=true&source=labnol
sheetnames=false&printtitle=false
pagenumbers=false&gridlines=false

我目前使用from googleapiclient.discovery import build编写了以下请求代码:

services = build('drive', 'v3', credentials=credentials)
services.files().export(fileId = google_sheet_id, mimeType = 'application/pdf').execute()

请问是否有方法将上述自定义设置添加到该请求中?

解决方案

Drive API的files.export方法不支持直接传入这些PDF导出的自定义参数,你需要改用Google Sheets API的spreadsheets.get接口来实现,把这些参数作为查询参数附加到请求里。

实现步骤

  • 先在Google Cloud控制台中启用Google Sheets API
  • 修改代码如下,传入所有自定义导出参数:
from googleapiclient.discovery import build

# 构建Sheets API服务实例
sheets_service = build('sheets', 'v4', credentials=credentials)

# 定义PDF导出的自定义参数
export_options = {
    'exportFormat': 'pdf',
    'size': '6.29921x23.2283',
    'portrait': 'true',
    'fitw': 'true',
    'source': 'labnol',
    'sheetnames': 'false',
    'printtitle': 'false',
    'pagenumbers': 'false',
    'gridlines': 'false'
}

# 发送请求获取PDF二进制内容
pdf_data = sheets_service.spreadsheets().get(
    spreadsheetId=google_sheet_id,
    **export_options
).execute()

# 将PDF内容写入本地文件
with open('custom_sheet_export.pdf', 'wb') as output_file:
    output_file.write(pdf_data)

说明

Google Sheets API的spreadsheets.get方法支持通过查询参数指定导出格式和打印配置,这些参数和浏览器导出PDF时的URL参数逻辑一致,直接传入就能生效。

内容的提问来源于stack exchange,提问作者Godoy32

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 17:08:10