- 您希望将 Google 电子表格转换为 PDF 格式,并将其创建为与 Google 电子表格相同的文件夹中的文件。
- 在这种情况下,PDF 文件是在 Google Drive 上创建的。
- 您希望通过 Python 使用 pydrive 来实现此目的。
问题和解决方法:
很遗憾,Google 电子表格无法使用 Google API 直接转换并导出到 Google Drive。在这种情况下,需要使用变通方法。在这个答案中,我想提出以下两种解决方法。
模式一:
在此模式中,您的目标是使用 pydrive 实现的。在这种情况下,电子表格以 PDF 文件的形式下载到本地 PC,并将 PDF 文件上传到 Google Drive 上电子表格的同一文件夹中。
示例脚本:
spreadsheet_id = '###' # Please set the Spreadsheet ID.
pdf_filename = 'sample.pdf'
drive = GoogleDrive(gauth)
# Download Spreadsheet as PDF file.
dl_file = drive.CreateFile({'id': spreadsheet_id})
dl_file.GetContentFile(pdf_filename, mimetype='application/pdf')
# Get parent folder ID of the Spreadsheet.
url = 'https://www.googleapis.com/drive/v3/files/' + spreadsheet_id + '?fields=parents'
headers = {'Authorization': 'Bearer ' + drive.auth.credentials.token_response["access_token"]}
res = requests.get(url, headers=headers)
# Upload the PDF file to the same folder of Spreadsheet.
up_file = drive.CreateFile({'parents': [{'id': res.json()['parents'][0]}]})
up_file.SetContentFile(pdf_filename)
up_file.Upload()
print('title: %s, mimeType: %s' % (up_file['title'], up_file['mimeType']))
- 为了获取电子表格的父文件夹ID,我使用了Drive API中的files.get方法
requests。
模式 2:
在此模式中,您的目标是使用由 Google Apps 脚本创建的 Web 应用程序实现的。在这种情况下,使用 Web 应用程序将电子表格转换为 PDF 格式,并在电子表格的同一文件夹中创建一个文件。所以这个过程只能在谷歌端运行。 python 脚本仅通过请求发送电子表格 ID。为此,请执行以下流程。
1。创建 Google Apps 脚本的新项目。
Web Apps 的示例脚本是 Google Apps 脚本。所以请创建一个 Google Apps Script 项目。
如果要直接创建,请访问https://script.new/。在这种情况下,如果您没有登录 Google,则会打开登录屏幕。所以请登录谷歌。这样,Google Apps Script 的脚本编辑器就打开了。
2。准备脚本。
请将以下脚本(Google Apps 脚本)复制并粘贴到脚本编辑器中。此脚本适用于 Web 应用程序。
function doGet(e) {
var spreadsheetId = e.parameter.id;
var file = DriveApp.getFileById(spreadsheetId);
var blob = file.getBlob();
var folder = file.getParents().next();
var pdfFile = folder.createFile(blob.setName(file.getName() + ".pdf"));
return ContentService.createTextOutput(pdfFile.getId());
}
3。部署 Web 应用程序。
- 在脚本编辑器上,通过“发布”->“部署为 Web 应用”打开一个对话框。
- 为“执行应用程序为:”选择“我”。
- 为“谁有权访问应用程序:”选择“任何人,甚至匿名”。
- 在这种情况下,不需要请求访问令牌。我认为作为测试用例,我推荐这个设置。
- 当然,您也可以使用访问令牌。届时,请将其设为“任何人”。
- 单击“部署”按钮作为新的“项目版本”。
- 自动打开“需要授权”对话框。
- 点击“查看权限”。
- 选择自己的帐户。
- 点击“此应用未验证”中的“高级”。
- 点击“转到###项目名称###(不安全)”
- 点击“允许”按钮。
- 点击“确定”。
- 复制 Web 应用程序的 URL。就像
https://script.google.com/macros/s/###/exec。
- 当您修改 Google Apps 脚本时,请重新部署为新版本。这样,修改后的脚本就会反映到 Web 应用程序中。请注意这一点。
3。使用 Web 应用程序运行函数。
这是一个用于请求 Web 应用程序的示例 Python 脚本。请设置您的网络应用 URL 和电子表格 ID。
import requests
spreadsheet_id = '###' # Please set the Spreadsheet ID.
url = 'https://script.google.com/macros/s/###/exec?id=' + spreadsheet_id
res = requests.get(url)
print(res.text)
参考资料: