簡體   English   中英

如何使用 Google Docs API 向 Word 文檔添加文本?

[英]How to add text to a Word document with Google Docs API?

我正在嘗試創建一個包含文本和圖像的 Word 文檔,但我什至無法顯示文本,我總是有一個空白文檔,它不會損害我的代碼。

如果有人能告訴我我做錯了什么,我將不勝感激。

gapi.client.docs.documents.create({
  resource: {
    title: "probando api de google docs",
    body: {
      content: [{
        paragraph: {
          elements: [{
            textRun: {
              content: "hi \n",
            },
          }, ],
        },
      }, ],
    },
  },
})

方法:documents.create

  • 使用請求中給出的標題創建一個空白文檔 請求中的其他字段,包括任何提供的內容,都將被忽略

如果要在新創建的文檔中插入文本,可以執行以下操作:

1.獲取新建文檔的文檔id。 您的創建請求應返回REST Resource:document您可以在其中獲取文檔 ID

示例響應正文:

{
  "title": "Test1",
  "body": {
    "content": [
      {
        "endIndex": 1,
        "sectionBreak": {
          "sectionStyle": {
            "columnSeparatorStyle": "NONE",
            "contentDirection": "LEFT_TO_RIGHT",
            "sectionType": "CONTINUOUS"
          }
        }
      },
      {
        "startIndex": 1,
        "endIndex": 2,
        "paragraph": {
          "elements": [
            {
              "startIndex": 1,
              "endIndex": 2,
              "textRun": {
                "content": "\n",
                "textStyle": {}
              }
            }
          ],
          "paragraphStyle": {
            "namedStyleType": "NORMAL_TEXT",
            "direction": "LEFT_TO_RIGHT"
          }
        }
      }
    ]
  },

....


  "revisionId": "xxxxxxxxxsamplerevisionid",
  "suggestionsViewMode": "SUGGESTIONS_INLINE",
  "documentId": "xxxxxxxxxsampledocumentid"
}

2. 使用documents.batchUpdate 方法使用您的文檔ID 將您的文本插入到文檔中。

樣品請求正文:

{
  "requests": [
    {
      "insertText": {
        "location": {
          "index": 1
        },
        "text": "Hello World"
      }
    }
  ]
}
  • 在此示例中,我使用InsertTextRequest在文檔中我想要的特定位置(位於索引 1 中)插入文本

Output:

在此處輸入圖像描述

附加說明:要了解有關 Google Docs 文檔的內部結構的更多信息:構成文檔的元素以及這些元素之間的關系、索引和定位。 參考這個鏈接: https://developers.google.com/docs/api/concepts/structure

了解有關請求方法和響應的更多信息。 參考這個鏈接: https://developers.google.com/docs/api/concepts/request-response

有關完整的 REST 資源,請參閱此處: https://developers.google.com/docs/api/reference/rest

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM