【问题标题】:How to create a Google Doc with regular text as the body?如何创建以常规文本为正文的 Google Doc?
【发布时间】:2021-01-02 21:22:18
【问题描述】:

我正在获取存储在 Google 表格中的信息并尝试在 Google 文档中整齐地格式化它。我正在使用 Google Docs API here,但我没有关注如何正确使用 JSON 表示的“正文:”部分。

为了简单起见,您将如何创建一个标题为“Test”且正文只是说“Hello world!”的新文档。如果需要,我正在使用 Python 3.7。

感谢您的帮助!

【问题讨论】:

    标签: python google-drive-api google-docs google-docs-api


    【解决方案1】:

    我相信你的目标如下。

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

    问题和解决方法:

    我认为在这种情况下,我想建议使用 Drive API。因为现阶段使用Google Docs API时,需要使用2次API调用,如下,因为documents.create的方法不能包含正文。

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

    所以,在这个答案中,我想建议在 Drive 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)
      

    参考资料:

    【讨论】:

    • 谢谢,这是对我问题的非常彻底的回答。最后一件事,我如何向特定用户授予编辑权限访问权限,因为似乎只有 Google 服务帐户才能访问此文件
    • @Tucker 感谢您的回复。关于你对how would I give editor permission access to specific users as it seems only the Google Service account can access this file的附加问题,在这种情况下,我认为可以使用“权限:创建”的方法。 Ref 示例脚本可以在stackoverflow.com/a/58088998/7108653 看到如果这不是您期望的答案,我很抱歉。
    猜你喜欢
    • 1970-01-01
    • 2020-10-01
    • 2021-12-26
    • 1970-01-01
    • 1970-01-01
    • 2021-12-15
    • 2015-10-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多