【问题标题】:Can I add a script to a Google Sheet using another script?我可以使用其他脚本将脚本添加到 Google 表格吗?
【发布时间】:2020-06-04 15:13:01
【问题描述】:

我有一个脚本 populate() 可以在 Google 表格上运行自动化脚本。我希望这个脚本可以在一百多个 Google 表格文件上运行。有没有办法编写一个脚本来添加(或至少运行)我对所有这些文件的 populate() 脚本?我更喜欢能够将脚本添加到每个文件,因为我们可能需要为每个文件多次运行脚本。否则,我将不得不手动将脚本复制/粘贴到每张纸上,这需要时间。

更新:删除了关于将 Excel 文件转换为 Google 表格的部分,因为我在另一个线程 here 上找到了答案。

【问题讨论】:

  • 编写一个与 google 兼容的脚本来打开文件夹中的每个文件,应用你的脚本并 dave。运行它,喝咖啡,然后等待完成。
  • 我认为问题标题与问题正文不匹配。 populate() 是什么?另请按照How to Ask 中的建议添加您的搜索/研究工作的简要说明。

标签: google-apps-script google-sheets google-drive-api


【解决方案1】:

解决方案

根据我从您的帖子中了解到的情况,您的问题是关于如何将 Drive 文件夹中的一系列 Excel 文件转换为 Google 表格,然后在其中执行功能。

为此,您可以遍历文件夹中的所有文件,并使用 Drive API 中的 Drive.insert 进行转换。为此,您必须在脚本中启用高级 Google 服务。如果您不知道如何操作,请关注these indications

以下脚本执行我认为您的目标,它具有不言自明的 cmets:

function convertExcelToGoogleSheets() {
  
  // Id of the folder where you have all your excel files
  var folderId = 'FOLDERID';
  var folder = DriveApp.getFolderById(folderId);
  
  // Get all the files in your folder and iterate over them
  var files = folder.getFiles();
  // For each file:
  while (files.hasNext()){
    var file = files.next();
    
    // Get its blob (content)
    var blob = file.getBlob();
    
    // Create the resource to insert the Google Sheet file. Put the same name
    // as the original and set the type of the file to Google sheets and its 
    // parent folder to where the excel files are located
    var resource = {
      title: file.getName(),
      mimeType: MimeType.GOOGLE_SHEETS,
      parents: [{id: folderId}],
    };
    // User Drive API to insert the actual file and get its ID
    var id = Drive.Files.insert(resource, blob).getId();
    // Whatever function you want to perform in the newly created Google Sheet
    // pasing the parameter of the file id
    myScript(id);  
    }
}

// Set the first cell of all the converted sheets to "IT WORKED"
function myScript(id){
  SpreadsheetApp.openById(id).getActiveSheet().getRange('A1').setValue('IT WORKED!');
}

编辑:如果您想为每个转换后的工作表运行脚本,您只需在 while 循环中调用它并将新文件 ID 作为参数传递,然后就可以使用脚本(记得把这个脚本封装在一个函数中)

我希望这对您有所帮助。让我知道您是否需要其他任何内容或者您是否不理解某些内容。 :)

【讨论】:

  • 谢谢马特奥。这解决了将它们转换为 Google 表格的第一个问题。但是,我的主要问题是能够将该脚本添加到每个文件中,我不知道该怎么做。
  • 我已经相应地编辑了我的答案以满足您的问题。如果您对此有任何疑问,请告诉我。 :D
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-15
  • 1970-01-01
  • 2018-05-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多