如何创建以常规文本为正文的Google文档?

2024-10-03 02:37:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在把存储在谷歌表格中的信息整理成谷歌文档的格式。我正在使用GoogleDocsAPIhere,但我不知道如何正确使用JSON表示的“body:”部分

为了简单起见,您将如何创建一个标题为“Test”的新文档,而其主体只是说“helloworld!”。如果需要,我将使用Python 3.7

谢谢你的帮助


Tags: 文档test信息json标题格式body整理
1条回答
网友
1楼 · 发布于 2024-10-03 02:37:03

我相信你的目标如下

  • how would you create a new document with the title "Test" and the body just saying "Hello world!".开始,我了解到您希望使用python将Hello world!的文本作为新的Google文档上传

问题和解决方法:

我认为在这种情况下,我想建议使用驱动API。因为在当前阶段,当使用Google Docs API时,需要使用2个API调用,如下所示,因为documents.create的方法不能包含文本体

  1. 使用documents.create方法创建新的Google文档Ref
  2. 使用documents.batchUpdate方法上载文本Ref

因此,在这个答案中,我建议在驱动API中使用Files: create方法Ref使用此方法时,您的目标可以通过一个API调用实现

使用googleapis for python的示例脚本如下所示

示例脚本:

在这种情况下,请使用Quickstart的授权脚本。在这种情况下,请使用https://www.googleapis.com/auth/drive作为作用域

drive = build('drive', 'v3', credentials=creds)
text = 'Hello world!'
media = MediaIoBaseUpload(io.BytesIO(text.encode('utf-8')), mimetype='text/plain', resumable=True)
file_metadata = {"name": "Test", "mimeType": "application/vnd.google-apps.document"}
file = drive.files().create(body=file_metadata, media_body=media).execute()
print(file)
  • 运行上述脚本时,将创建文件名为Test的新Google文档,并且正文的文本为Hello world!
  • 在这种情况下,也使用from googleapiclient.http import MediaIoBaseUpload

注:

  • 如果需要使用Google Docs API,还可以使用以下脚本。在本例中,结果与上面的示例脚本相同

      docs = build('docs', 'v1', credentials=creds)
      text = 'Hello world!'
      res1 = docs.documents().create(body={"title": "Test"}).execute()
      requests = [{"insertText": {"location": {"index": 1}, "text": text}}]
      res2 = docs.documents().batchUpdate(documentId=res1.get('documentId'), body={"requests": requests}).execute()
      print(res2)
    

参考文献:

相关问题 更多 >