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

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

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

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

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

最佳答案

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

关于java - 无法通过 Docs API 向新的 Google Doc 添加文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57300083/

相关文章:

java - JTable 中的 setPreferredScrollableViewportSize() 与 setFillsViewportHeight()

jvm - 如何在当前机器上运行jvm

google-api - 在 Google 文档中打开图片

python - 使用 gdata 的托管域的 google 数据 API 的 OAuth 身份验证失败

java - 抛硬币代码中的双重答案

java - 双括号初始化和序列化

java - 使用 Jackson 进行 JSON 反序列化 : No suitable constructor found for type - providing default constructor or annotate constructor is imposible

ruby - Google Drive API 的客户端登录

php - 更新后有一个空文件

javascript - 通过 GAS 将存储在云端硬盘文件夹中的图像添加到 Google 文档