Google apps script 谷歌代码不起作用
我是谷歌应用程序脚本编程新手。最近,我试着跟随,但看起来他们的代码已经过时了。然而,我仍然想做教程所做的事情,除了它现在将在Google Drive中搜索文件 以下是我的代码:Google apps script 谷歌代码不起作用,google-apps-script,google-sheets,google-apps,Google Apps Script,Google Sheets,Google Apps,我是谷歌应用程序脚本编程新手。最近,我试着跟随,但看起来他们的代码已经过时了。然而,我仍然想做教程所做的事情,除了它现在将在Google Drive中搜索文件 以下是我的代码: function onOpen() { var spreadsheet = SpreadsheetApp.getActiveSpreadsheet(); var searchMenuEntries = [ { name: "Search in all files",
function onOpen() {
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var searchMenuEntries = [
{
name: "Search in all files",
functionName: "search"
}
];
spreadsheet.addMenu("Search Document", searchMenuEntries);
}
function search() {
// Prompt the user for a search term
var searchTerm = Browser.inputBox("Enter the string to search for:");
// Get the active sheet
var sheet = SpreadsheetApp.getActiveSheet();
// Set up the spreadsheet to display the results
var headers = [
["File Name",
"File Type",
"URL"
]
];
sheet.clear();
sheet.getRange("A1:C1").setValues(headers);
// Search the files in the user's Drive for the search term
var files = DriveApp.getFilesByName(searchTerm);
// Loop through the results and display the file name, file type, and URL
var i = 0;
while (files.hasNext()) {
files = files.next();
sheet.getRange(i+2, 1, 1, 1).setValue(files.getName());
sheet.getRange(i+2, 2, 1, 1).setValue(files.getMimeType());
sheet.getRange(i+2, 3, 1, 1).setValue(files.getDownloadUrl());
i++;
}
}
当我试着运行代码时,没有出现给我警告的重大错误。但是,代码不起作用,Google Sheets中的输出如下:
+---------------+----------------+----------------+
| File name | File type | URL |
+---------------+----------------+----------------+
| | | |
+---------------+----------------+----------------+
尽管我很确定我的驱动器中有文件匹配项。我试图调试代码,但while循环似乎没有执行。任何帮助都将不胜感激 这段代码中有一些拼写错误,我不知道您是在哪里/如何复制的。。。以下是工作代码(参见代码中的注释): 编辑: 顺便说一句,这个脚本实现得很糟糕,它在循环中使用API调用,这是非常低效的。。。 下面是一个更快的版本(也更紧凑) 注: 要更改搜索条件,只需使用DriveApp.search调用并添加参数 查看文件内容的示例:
var files = DriveApp.searchFiles('fullText contains "'+searchTerm+'"');
谢谢@Serge insas!但是,是否可以找到包含查询的文件名,而不只是找到具有该名称的文件?原因当前搜索
xyz
仅当存在名为xyz
的文件时有效(结果中将不包括xyza
)。
function search() {
// Prompt the user for a search term
var searchTerm = Browser.inputBox("Enter the string to search for:");
// Get the active sheet
var sheet = SpreadsheetApp.getActiveSheet();
// Set up the spreadsheet to display the results
var result = [];
result.push(["File Name","File Type","URL"])
// Search the files in the user's Drive for the search term
var files = DriveApp.getFilesByName(searchTerm);
// Loop through the results and display the file name, file type, and URL
while (files.hasNext()) {
var file = files.next();
result.push([file.getName(),file.getMimeType(),file.getDownloadUrl()]);
}
sheet.getRange(1,1,result.length,result[0].length).setValues(result);
}
var files = DriveApp.searchFiles('fullText contains "'+searchTerm+'"');