我的代码类似于文件搜索引擎,它接受您正在查找的关键字,对用户谷歌驱动器中的所有文件进行全文搜索,并通过将其显示在中返回文件名,url源和文件夹一个电子表格。 代码:
function search(Phrase, FolderID) {
// Prompt the user for a search term
var searchTerm = Browser.inputBox("Enter the string to search for:");
// Get the active spreadsheet and the active sheet
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
// Set up the spreadsheet to display the results
var headers = [["File Name", "Folder", "URL"]];
sheet.clear();
sheet.getRange("A4:C4").setValues(headers);
// Search the files in the user's Google Drive for the search term based on if the word is included in thefile or name
// Search Reference Guide: https://developers.google.com/apps-script/reference/drive/drive-app#searchFiles(String)
var files = DriveApp.searchFiles("fullText contains '"+searchTerm.replace("'","\'")+"'");
//var SearchString = 'fullText contains "' + Phrase + '" and "' + FolderID + '" in parents';
//var files = DriveApp.searchFiles(SearchString);
// create an array to store our data to be written to the sheet
var output = [];
// Loop through the results and get the file name, URL, and Folder
while (files.hasNext()) {
var file = files.next();
var name = file.getName();
//var type = file.getMimeType(); //File type
var url = file.getUrl();
var folderNames = "";
var folders = file.getParents();
while (folders.hasNext()) {
var folder = folders.next();
//Logger.log(folder.getName());
folderNames += folder.getName() + ", ";
}
// push the file details to our output array (essentially pushing a row of data)
output.push([name, folderNames, url]);
}
// write data to the sheet
sheet.getRange(5, 1, output.length, 3).setValues(output);
}
我绝对是编码/谷歌脚本的初学者,所以我只想要一些建议(如果有的话)来帮助减少代码完成一次运行并获得结果所需的时间,因为目前我必须等待 5- 15秒出结果。
使用 Drive API 怎么样?虽然我不确定这个建议是否对您的情况有用,但您可以尝试一下这个脚本吗?修改后的脚本如下。当您使用此脚本时,请在高级 Google 服务和 API 控制台启用 Drive API。
function search(Phrase, FolderID) {
// Prompt the user for a search term
var searchTerm = Browser.inputBox("Enter the string to search for:");
// Get the active spreadsheet and the active sheet
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
sheet.clear();
// Below script was added.
var optionalArgs = {
q: "fullText contains '"+searchTerm.replace("'","\'")+"'",
fields: "items(alternateLink,parents/id,title)"
};
var files = Drive.Files.list(optionalArgs).items; // Retrieve files by search text.
var res = files.map(function(e){return [e.title, e.parents.map(function(f){return DriveApp.getFolderById(f.id).getName()}).join(", ") , e.alternateLink]});
var values = [["File Name", "Folder", "URL"]];
Array.prototype.push.apply(values, res);
sheet.getRange(4, 1, values.length, 3).setValues(values);
}
如果这对您的情况没有用,我很抱歉。
Google Apps 脚本可能无法满足您的性能期望,因为它的目的是成为一个快速开发平台,而不是高性能平台。
但是,您可以通过使用高级服务并减少电子表格的读写操作来稍微提高性能。这可以使用高级工作表服务/工作表 API 的 batchUpdate 方法来完成。