使用GS迭代工作表,而列中有任何数据

时间:2016-03-03 15:10:21

标签: google-apps-script google-sheets

我需要做一个小脚本,它的基本思想是在一列中有一个名字,另一行有一些随机信息(在右边)。这张纸有一些计数(事先未知),所以它们就像

 John   39483984
 George 3498349
 Layla  23948

因此,用户可以输入任意数量的此类简单记录,我的脚本必须为每个名称创建一个文件(文件名称相同),并将该号码写入该文件。我设法找到了如何创建文件(虽然仍然无法找到如何在当前文件夹中创建文件,与工作表所在的位置相同 - 这只是一个侧面问题,但如果您知道如何操作,请告诉我)。唯一真正的问题是遍历记录。我的想法是逐个浏览它们并在有空记录时停止 - 基本策略,但我无法找到如何实现它(是的!)。有范围功能,但我应该事先知道范围;还有一个获取选定单元格的功能,但这需要用户选择记录,这很奇怪。

所以,如果它存在于这个令人沮丧的Google Script中,请建议我一个解决方案。

1 个答案:

答案 0 :(得分:1)

function createFilesForEachNameInSheet() {

  // First, you connect to the spreadsheet, and store the connection into a variable
  var ss = SpreadsheetApp.openById("SPREADSHEET_KEY_GOES_HERE"); // you do know how to get the spreadsheet key, right?

  // Then, you take the sheet from that spreadsheet
  var sheet = ss.getSheetByName("Sheet1");

  // Then, the "problematic range". You get the ENTIRE range, from end to end, as such:
  var wholeRange = sheet.getRange(1,1,sheet.getLastRow(),sheet.getLastColumn());

  // Then, you fetch its values:
  var rangeValues = wholeRange.getValues();

  // At this point you have a bi-dimensional array, representing the rows and columns. 
  // Assuming you have 2 columns, in the first column you have the names, and in the second you have the unknown value
  // You need to use the already known for loop, iterate over all the data, and store it first in an object, so that you create the file only ONCE.

  var objectData = {};

  for (var i=0;i<rangeValues.length;i++) {
    var thisName = rangeValues[i][0];
    var thisValue = rangeValues[i][1];
    if (objectData.thisName == undefined) objectData.thisName = [];
    objectData.thisName.push(thisValue);
  }

  // Now we have our values grouped by name. 
  // Let's create a file for each name.

  for (var name in objectData) {
    DriveApp.createFile(name, objectData.name.join("\n"));
  }

  // NOTE: if you want to create into a specific folder, you first target it, using the DriveApp:
  var folders = DriveApp.getFoldersByName("the folder name goes here");

  // folders variable is now an iterator, containing each folder with that name.
  // we will iterate over it as follows, and select the one we want. 
  // the logic for it, you'll select one of your choice:

  while (folders.hasNext()) {
    var thisFolder = folders.next();
    if (/* condition to check if we found the right folder */) {
      thisFolder.createFile(name, objectData.name.join("\n"))
    }
  }

}