我正在尝试使用google驱动器API更新google驱动器文档中的单个文本,如{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);
}
}
我相信你的目标和目前的情况如下。
- 您想在Google文档中将
{{firstname}}
替换为hello world
- 您希望使用Node.js的googleapi来实现这一点
- 您已经能够使用Docs API获取和设置Google文档的值
遗憾的是,驱动器API中的更新方法中没有replaceAllText
请求。在这种情况下,请使用Google Docs API的批量更新方法。当您的脚本被修改时,它变成如下。
修改的脚本:
在这种情况下,请使用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文档的值。请小心
参考文献:
- 方法:documents.batchUpdate
- 替换所有文本请求