首页 > 解决方案 > Unable to add text to new Google Doc via Docs API

问题描述

My program is creating documents and each document has text that needs to go into it. Any attempt to call an InsertTextRequest invokes an error.

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();
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"
}

Even trying to add a newline character before adding the text does not fix this issue.

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

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

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();

This also invokes the same error. How can I properly add text?

标签: javagoogle-docs-api

解决方案


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


推荐阅读