Apps脚本输出到定义的范围而不是整个工作表

时间:2018-02-06 12:40:39

标签: google-apps-script google-sheets

没有经验的编码员在这里有第一篇文章。管理以适应我喜欢的脚本,但是遇到这个范围与工作表问题,我希望有人可以提供帮助。

这是一个列出所有文件的脚本。 Google Drive中的文件夹由FolderID提供。该脚本为文件夹名称创建一个新选项卡,或者如果该选项卡已存在则更新工作表。

我认为该脚本使用

sheet.clearContent();
sheet.appendRow(data);

将内容写入工作表。

该脚本有效地只写入4列,A:D。我一直在尝试将脚本的输出限制为A:D列,因此在重新运行脚本时,表单的其余部分保持不变。目前,在重新运行脚本时,整个工作表都会获得clear.Content(ed)

我一直在尝试像sheet.getRange(A1:D).clearContent()这样的事情,并与range.setValues(Data)一起定义范围,但我无法获得理想的结果。

这是我有的脚本,请帮助我只输出A:D列而不改变或注意其他列中的内容

// Create menu button with function items
function onOpen() {
  var ui = SpreadsheetApp.getUi();
  ui.createMenu('Fetch Files')
      .addItem('Files & Folders', 'ListAll')
      .addItem('Folders Only', 'ListFolders')
      .addToUi();
}

var IDCell = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Setup"); //Set Sheet name which contains Folder ID
var folderId = IDCell.getRange("C2").getValue();  //Set Cell that contains Folder ID

// Main function 1: List all folders, & write into the current sheet.
function ListFolders(){
  getFolderTree(folderId, false);
};

// Main function 2: List all files & folders, & write into the current sheet.
function ListAll(){
  getFolderTree(folderId, true); 
};

// Get Folder Tree
function getFolderTree(folderId, listAll) {
  try {
    // Get folder by id
    var parentFolder = DriveApp.getFolderById(folderId);

    // Initialise the sheet - Create sheet with folder name if there is none
    var ss = SpreadsheetApp.getActive();
    var file, data, sheet = ss.getSheetByName(parentFolder.getName());
      if (sheet) {
    Logger.log("found");
  }
  else {
    sheet = ss.insertSheet(parentFolder.getName());
  }
    // Clear range & set headers
    sheet.clearContent();
    sheet.appendRow(["Full Path", "Name", "URL", "Type"]);

    // Get files and folders
    getChildFolders(parentFolder.getName(), parentFolder, data, sheet, listAll);

  } catch (e) {
    Logger.log(e.toString());
  }
};

// Get the list of files and folders and their metadata in recursive mode
function getChildFolders(parentName, parent, data, sheet, listAll) {
  var childFolders = parent.getFolders();

  // List folders inside the folder
  while (childFolders.hasNext()) {
    var childFolder = childFolders.next();
    // Logger.log("Folder Name: " + childFolder.getName());
    data = [ 
      parentName + "/" + childFolder.getName(),
      childFolder.getName(),
      childFolder.getUrl(),
      ];

    // Write
    sheet.appendRow(data);

    // List files inside the folder
    var files = childFolder.getFiles();
    while (listAll & files.hasNext()) {
      var childFile = files.next();
      // Logger.log("File Name: " + childFile.getName());
      data = [ 
        parentName + "/" + childFolder.getName() + "/" + childFile.getName(),
        childFile.getName(),
        childFile.getUrl(),
        childFile.getMimeType(),
        ];

      // Write
      sheet.appendRow(data);
    }

    // Recursive call of the subfolder
    getChildFolders(parentName + "/" + childFolder.getName(), childFolder, data, sheet, listAll);  
  }
};

1 个答案:

答案 0 :(得分:0)

您正在寻找的仅清除特定细胞的功能是

sheet.getRange("A2:D").clearContent()

当您获得a1Notation的范围,即“A1:D1”时,您需要将其作为字符串“A1:D”提供。同样,要将数据添加到特定单元格,您将执行以下操作:

sheet.getRange("A1").setValue("Your value here")

正如您所知,getRange(a1Notation)的缺点是对不同长度的数据的动态或不断发展的操作不友好。因此,您可以使用函数的不同变体

getRange(row, column, numRows, numColumns)

您的最终代码如下所示:

var sheetData = []   //Global variable (array) that can be accessed by every function
function onOpen() {
  var ui = SpreadsheetApp.getUi();
  ui.createMenu('Fetch Files')
      .addItem('Files & Folders', 'ListAll')
      .addItem('Folders Only', 'ListFolders')
      .addToUi();
}

var IDCell = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Setup"); //Set Sheet name which contains Folder ID
var folderId = IDCell.getRange("C2").getValue();  //Set Cell that contains Folder ID

// Main function 1: List all folders, & write into the current sheet.
function ListFolders(){
  getFolderTree(folderId, false);
};

// Main function 2: List all files & folders, & write into the current sheet.
function ListAll(){
  getFolderTree(folderId, true); 
};

// Get Folder Tree
function getFolderTree(folderId, listAll) {
  try {
    // Get folder by id
    var parentFolder = DriveApp.getFolderById(folderId);

    // Initialise the sheet - Create sheet with folder name if there is none
    var ss = SpreadsheetApp.getActive();
    var file, data, sheet = ss.getSheetByName(parentFolder.getName());
      if (sheet) {
    Logger.log("found");
        sheet.getRange("A2:D").clearContent()  
         //You only need to clear if the sheet is found

  }
  else {
    sheet = ss.insertSheet(parentFolder.getName());
    sheet.appendRow(["Full Path", "Name", "URL", "Type"]);
    //New Sheet would be empty so no need to clearhere
  }
    // Clear range & set headers


    // Get files and folders
    getChildFolders(parentFolder.getName(), parentFolder, data, sheet, listAll);
    Logger.log(sheetData)
    // You write the data from sheetData once at the end. 
    sheet.getRange(2,1,sheetData.length,4).setValues(sheetData)
  } catch (e) {
    Logger.log(e.toString());
  }
};

// Get the list of files and folders and their metadata in recursive mode
function getChildFolders(parentName, parent, data, sheet, listAll) {
  var childFolders = parent.getFolders();

  // List folders inside the folder
  while (childFolders.hasNext()) {
    var childFolder = childFolders.next();
    // Logger.log("Folder Name: " + childFolder.getName());
    data = [ 
      parentName + "/" + childFolder.getName(),
      childFolder.getName(),
      childFolder.getUrl(),
      "Folder"
      ];

    // Write
    sheetData.push(data)   //Instead of appending row each time
    // you push the data to the global array 

    // List files inside the folder
    var files = childFolder.getFiles();
    while (listAll & files.hasNext()) {
      var childFile = files.next();
      // Logger.log("File Name: " + childFile.getName());
      data = [ 
        parentName + "/" + childFolder.getName() + "/" + childFile.getName(),
        childFile.getName(),
        childFile.getUrl(),
        childFile.getMimeType(),
        ];

      // Write
      sheetData.push(data)
    }

    // Recursive call of the subfolder
    getChildFolders(parentName + "/" + childFolder.getName(), childFolder, data, sheet, listAll);  
  }
};

最终注释:请查看下面使用的各种概念的文档 Global Variables
Array.push
Range.setValues()