简体   繁体   English

在谷歌应用脚​​本中阅读多个电子表格

[英]Reading multiple spreadsheets in google app script

I'm trying to get all text from a specific cell of all spreadsheets in a folder. 我正在尝试从文件夹中所有电子表格的特定单元格中获取所有文本。 My current issue is I can only read them in as a file type which doesn't allow me to access the getRange() function. 我目前的问题是我只能将它们作为一种文件类型读取,不允许我访问getRange()函数。

Here's my code so far. 到目前为止,这是我的代码。

function createLog() {

  var folder = DriveApp.getFolderById("id#");//not placing actual id for privacy

  var contents = folder.getFiles();

  var data; //array for relevant text

  var file; 

  var d = new Date();

  var log = SpreadsheetApp.create("Events log "+d.getMonth()+"/"+d.getDay());



 while(contents.hasNext()) {

    file = contents.next();

     file.getRange("A6");//error is here because it is a file type not a spreadsheet



  }


  for(var i =0; i<contents.length;i++){

log.getRange(0,i).setValue(data[i]); 

  }

}

Once you have the list of files you need to open them with SpreadsheetApp. 获得文件列表后,需要使用SpreadsheetApp打开它们。 Then you can work on Spreadsheet using the Sheet and Range functions. 然后,您可以使用工作表和范围功能处理电子表格。

var spreadsheet = SpreadsheetApp.openById(file.getId());
var sheet = spreadsheet.getSheetByName('your sheet name');
var value = sheet.getRange("A6");

See: 看到:

https://developers.google.com/apps-script/reference/spreadsheet/spreadsheet-app https://developers.google.com/apps-script/reference/drive/file#getId() https://developers.google.com/apps-script/reference/spreadsheet/spreadsheet-app https://developers.google.com/apps-script/reference/drive/file#getId()

Cameron's answer is correct but I suggest to open spreadsheets by ID instead of names because in Google Drive many files can have the same name... Below is a simplified demo code to test the idea and a few comments to highlight what needs to be adjusted Cameron的答案是正确的,但我建议按ID而不是名字打开电子表格,因为在Google云端硬盘中,许多文件可以使用相同的名称...下面是一个简化的演示代码来测试这个想法和一些注释,以突出显示需要调整的内容

function createLog() {
  var folder = DriveApp.getFolderById("0B3###############ZMDQ");//not placing actual id for privacy
  var contents = folder.getFilesByType(MimeType.GOOGLE_SHEETS);
  var data; //array for relevant text
  var fileID,file,sheet; 
  var data = [];
  var d = new Date();
  var log = SpreadsheetApp.create("Events log "+d.getMonth()+"/"+d.getDay());

  while(contents.hasNext()) {
    file = contents.next();
    Logger.log('Sheet Name = '+file.getName());
    fileID = file.getId();
    sheet = SpreadsheetApp.openById(fileID).getSheets()[0];// this will get the first sheet in the spreadsheet, adapt to your needs
    data.push([sheet.getRange("A6").getValue()]);// add a condition before this line to get only the data you want
  }
  log.getActiveSheet().getRange(1,1,data.length, data[0].length).setValues(data); 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM