【问题标题】:How to update specific text in google drive docs with node.js {name}如何使用 node.js {name} 更新谷歌驱动器文档中的特定文本
【发布时间】:2021-05-29 22:05:01
【问题描述】:

我正在尝试使用 google drive API 在 google drive 文档中更新像 {name} 这样的单个文本。例如,如果我在文档中有变量 name = 'hello world',则文本 {name} 应替换为 'hello world'。任何帮助表示赞赏。

async function replaceText() {
  try {
    const id = "144zvxc_xQUuEqKgS5BfjOKMQsfegFI2Vey";
    
    drive.files.update(
      {
        fileId: id,
        requests = [
            {
              replaceAllText: {
                containsText: {
                  text: "{{firstname}}",
                  matchCase: true,
                },
                replaceText: 'hello world',
              },
            },
          ]
      },
    );
    console.log(response);
  } catch (error) {
    console.log(error.message);
  }
}

【问题讨论】:

  • 关于I'm trying to update a single text like {name} in a google drive docs with google drive API.,很遗憾,Drive API 的更新方法中没有replaceAllText 请求。那么在这种情况下,使用 Google Docs API 怎么样?因为replaceAllText 用于Docs API 中的batchUpdate 方法。 Ref
  • 非常感谢#Tanaike,这正是我正在寻找的东西,不幸的是我不知道应该在哪里设置这些值。你有什么想法或例子会很棒。再次感谢您的帮助。
  • 感谢您的回复。从您对Have you any idea or example could be great. 的回复中,我发布了使用 Google Docs API 修改脚本的答案。你能确认一下吗?如果这不是您期望的方向,我深表歉意。

标签: node.js google-docs-api


【解决方案1】:

我相信你的目标和你目前的情况如下。

  • 您想在 Google 文档中将 {{firstname}} 替换为 hello world
  • 您希望使用 googleapis for Node.js 来实现此目的。
  • 您已经能够使用 Docs API 获取和放置 Google Document 的值。

很遗憾,Drive API 的更新方法中没有replaceAllText 请求。在这种情况下,请使用 Google Docs API 的 batchUpdate 方法。当你的脚本被修改后,变成如下。

修改脚本:

在这种情况下,请使用https://www.googleapis.com/auth/documents的范围。

const docs = google.docs({ version: "v1", auth }); // Please use `auth` of your script.
const documentId = "###"; // Please set your Google Document ID.

const requests = [
  {
    replaceAllText: {
      containsText: {
        text: "{{firstname}}",
        matchCase: true,
      },
      replaceText: "hello world",
    },
  },
];
docs.documents.batchUpdate(
  {
    auth,
    documentId: documentId,
    requestBody: {
      requests,
    },
  },
  (err, res) => {
    if (err) {
      console.log(e);
      return;
    }
    console.log(res.data);
  }
);
  • 当您想用hello world替换{name}时,请将上面的脚本从text: "{{firstname}}",修改为text: "{name}",

注意:

  • 在此修改中,假设您已经能够使用 Google Docs API 获取和放置 Google Document 的值。请注意这一点。

参考资料:

【讨论】:

  • 你是最好的,我不知道它是谷歌文档的特定 API,我认为谷歌驱动器的 API 负责替换文本。你救了我的命,非常感谢你的支持。
  • @Alejandro Tamayo 欢迎您。谢谢你让我知道。我很高兴你的问题得到了解决。如果您的问题得到解决,请按接受按钮。与您有相同问题的其他人也可以将您的问题作为可以解决的问题。我认为您的问题和解决方案将对他们有用。如果找不到按钮,请随时告诉我。 stackoverflow.com/help/accepted-answer
  • @AlejandroTamayo 出于文档目的,如果可以的话,请接受对您有帮助的答案 (✓) - 它可以帮助将来遇到相同问题的其他人也找到解决方案:)跨度>
猜你喜欢
  • 2016-06-22
  • 2023-03-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-13
  • 1970-01-01
  • 2015-01-15
相关资源
最近更新 更多