无法通过 Docs API 向新的 Google Doc 添加文本

wys*_*koj 4 java google-docs-api

我的程序正在创建文档,每个文档都有需要输入的文本。任何InsertTextRequest调用调用的尝试都会引发错误。

List<Request> requests = new ArrayList<>();

requests.add(new Request().setInsertText(new InsertTextRequest()
                .setText("Simple test.")
                .setLocation(new Location().setIndex(0))));

BatchUpdateDocumentRequest body = new BatchUpdateDocumentRequest()
                .setRequests(requests);

BatchUpdateDocumentResponse response = docService.documents()
                .batchUpdate(file.getId(), body).execute();
Run Code Online (Sandbox Code Playgroud)
Exception in thread "main" com.google.api.client.googleapis.json.GoogleJsonResponseException: 400 Bad Request
{
  "code" : 400,
  "errors" : [ {
    "domain" : "global",
    "message" : "Invalid requests[0].insertText: The insertion index must be inside the bounds of an existing paragraph. You can still create new paragraphs by inserting newlines.",
    "reason" : "badRequest"
  } ],
  "message" : "Invalid requests[0].insertText: The insertion index must be inside the bounds of an existing paragraph. You can still create new paragraphs by inserting newlines.",
  "status" : "INVALID_ARGUMENT"
}
Run Code Online (Sandbox Code Playgroud)

即使在添加文本之前尝试添加换行符也无法解决此问题。

Exception in thread "main" com.google.api.client.googleapis.json.GoogleJsonResponseException: 400 Bad Request
{
  "code" : 400,
  "errors" : [ {
    "domain" : "global",
    "message" : "Invalid requests[0].insertText: The insertion index must be inside the bounds of an existing paragraph. You can still create new paragraphs by inserting newlines.",
    "reason" : "badRequest"
  } ],
  "message" : "Invalid requests[0].insertText: The insertion index must be inside the bounds of an existing paragraph. You can still create new paragraphs by inserting newlines.",
  "status" : "INVALID_ARGUMENT"
}
Run Code Online (Sandbox Code Playgroud)

这也会调用相同的错误。如何正确添加文本?

wys*_*koj 9

Location对象的索引设置为 1,因为它是 1 索引的。

  • 我猜除了内部团队之外,只有我们三个人使用过 Google API。哈哈。:D (3认同)
  • 发布问题后几分钟就解决了这个问题。API 文档中没有提到它是 1 索引的事实。 (2认同)