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

如何通过API创建带内容的Google Docs并更新文档内容?

如何通过API创建带内容的Google Docs并更新文本

你目前用Drive API创建空白Google Docs的代码没问题,但Drive API本身不支持直接编辑Docs内容,需要结合Google Docs API来实现内容的添加和更新。下面分两种场景给出实现方案:

一、创建文档时直接添加内容

方案1:上传本地文本文件转换为Docs

通过上传一个包含内容的本地文本文件(如TXT),让Drive自动转换为Google Docs格式,创建后的文档直接带内容:

from googleapiclient.http import MediaFileUpload

file_metadata = {
    'name': 'docs_name',
    'parents': [folder_id],
    'mimeType': 'application/vnd.google-apps.document'
}
# 本地文本文件的MIME类型设为text/plain
media = MediaFileUpload('content.txt',
                        mimetype='text/plain',
                        resumable=True)
try:
    doc = drive_service.files().create(body=file_metadata,
                                        media_body=media,
                                        fields='id').execute()
    documentId = doc.get("id")
    print(f"带内容的文档已创建,ID: {documentId}")
except HttpError as error:
    print(f'An error occurred: {error}')

方案2:创建空白文档后立即插入内容

先创建空白文档,再调用Docs API的batchUpdate接口插入内容,无需依赖本地文件:

  1. 先初始化Docs API服务:
from googleapiclient.discovery import build

docs_service = build('docs', 'v1', credentials=credentials)
  1. 结合原创建逻辑添加内容:
# 原创建空白文档代码
doc_metadata = {
    'name': 'docs_name',
    'parents': [folder_id],
    'mimeType': 'application/vnd.google-apps.document'
}
try:
    doc = drive_service.files().create(body=doc_metadata).execute()
    documentId = doc.get("id")
    
    # 调用Docs API插入初始内容
    requests = [
        {
            'insertText': {
                'location': {
                    'index': 1,  # Docs内容索引从1开始,空文档初始位置为1
                },
                'text': '这是文档的初始内容\n第二行文本内容'
            }
        }
    ]
    docs_service.documents().batchUpdate(
        documentId=documentId,
        body={'requests': requests}
    ).execute()
    print(f"文档创建并添加内容成功,ID: {documentId}")
except HttpError as error:
    print(f'An error occurred: {error}')

二、后续更新已有文档的内容

使用Docs API的batchUpdate方法,可实现内容的清空、插入、修改等操作,示例如下:

def update_docs_content(document_id, new_text):
    try:
        # 可选:清空原有内容(根据需求调整范围)
        clear_request = [
            {
                'deleteContentRange': {
                    'range': {
                        'startIndex': 1,
                        'endIndex': 100  # 可根据实际内容长度调整,或先调用get接口获取文档长度
                    }
                }
            }
        ]
        docs_service.documents().batchUpdate(
            documentId=document_id,
            body={'requests': clear_request}
        ).execute()
        
        # 插入新内容
        insert_request = [
            {
                'insertText': {
                    'location': {'index': 1},
                    'text': new_text
                }
            }
        ]
        docs_service.documents().batchUpdate(
            documentId=document_id,
            body={'requests': insert_request}
        ).execute()
        print("文档内容更新成功")
    except HttpError as error:
        print(f'An error occurred: {error}')

# 调用示例
update_docs_content(documentId, "这是更新后的文档内容")

注意事项

  • 需在Google Cloud Console中同时启用Drive API和Docs API
  • 认证凭据(credentials)需拥有目标文件夹的写入权限,以及Docs文档的编辑权限
  • Docs API的内容索引从1开始,空文档的初始内容长度为1(仅包含段落标记)

内容的提问来源于stack exchange,提问作者pedro.galva

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 12:17:26