如何使用node.js{name}更新google drive文档中的特定文本

如何使用node.js{name}更新google drive文档中的特定文本,node.js,google-docs-api,Node.js,Google Docs Api,我正在尝试用GoogleDrive API更新GoogleDrive文档中的一个文本,如{name}。例如,如果在文档中有变量名='hello world',则文本{name}应替换为'hello world'。感谢您的帮助 async function replaceText() { try { const id = "144zvxc_xQUuEqKgS5BfjOKMQsfegFI2Vey"; drive.files.update(

我正在尝试用GoogleDrive API更新GoogleDrive文档中的一个文本,如{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);
  }
}

我相信你的目标和现状如下

  • 您想在Google文档中将
    {{firstname}}
    替换为
    hello world
  • 您希望使用googleapis for Node.js实现这一点
  • 您已经能够使用DocsAPI获取和放置Google文档的值
不幸的是,驱动器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}
    时,请将上述脚本从
    文本:{{firstname}},
    修改为
    文本:{name},
注:
  • 在这次修改中,它假设您已经能够使用Google Docs API获取并输入Google文档的值。请注意这一点。
参考资料:

关于
我正在尝试使用google drive API更新google drive文档中的单个文本,如{name}。
,不幸的是,在drive API的更新方法中没有
replaceAllText
请求。那么在这种情况下,如何使用谷歌文档API?因为
replaceAllText
用于Docs API中的batchUpdate方法。非常感谢#Tanaike这正是我想要的,不幸的是,我不知道应该在哪里设置这些值。你有什么好主意或好例子吗。再次感谢您的帮助,谢谢您的回复。从您对
的回复中,您是否有任何想法或示例会很棒。
,我发布了一个关于使用Google Docs API修改脚本的答案。你能确认一下吗?如果这不是你期望的方向,我很抱歉。你是最好的,我不知道这是谷歌文档的一个特定API,我想谷歌驱动器的API应该负责替换文本。您救了我的命,非常感谢您的支持。@Alejandro Tamayo欢迎您。谢谢你让我知道。我很高兴你的问题解决了。如果您的问题已解决,请按“接受”按钮。与您有相同问题的其他人也可以将您的问题作为可以解决的问题。我认为你的问题和解决方案对他们会有帮助。如果你找不到按钮,尽管告诉我@AlejandroTamayo,仅供参考,如果可以,请接受答案(✓) 这对你很有帮助——它还可以帮助将来遇到同样问题的其他人找到解决方案:)