简体   繁体   中英

In GAS, reading col of data in multiple sheets in spreadsheet via loop

I am trying to read data from GAS (Google Apps Scripts) across multiple sheets in a spreadsheet and am having trouble figuring out how to do this.

BACKGROUND ON HOW SPREADSHEET IS SETUP

The spreadsheet is setup with multiple sheets (tabs), each with a unique name. I only care about a subset of sheets which is determined while my code is running, with the names of those sheets being stored in an array. In this example let's assume the names of the 3 sheets I care about are strored in an array:

sheetNames = ["Sheet1", "Sheet3", "Sheet7"]

All of the sheets have the same column headers and a different number of rows. The first column, column A, includes unique IDs, and the remaining columns include the rest of the data.

So for instance, the Sheet1 looks like this: 在此处输入图片说明

MY QUESTION

My Goal: I am trying to read a column of the IDs in column A from each of Sheet1, Sheet3, and Sheet7, and store that data for later use.

Here is the code I have so far:

// For this case, assume sheetNames = ["Sheet1", "Sheet3", and "Sheet7"]

for (var i=0; i<sheetNames.length; i++) {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetNames[i]);
  var values = sheet.getRange(2, 1, sheet.getLastRow()-1, 1).getValues();
}

The problem with what I have so far (of course :) ) is that the variable values is overwritten each iteration through the loop. But I'm a bit stuck.

What I would like to do is have sorta like an array of arrays so that values[0] contains an array with column A from Sheet1, values[1] contains an array with column A from Sheet3, etc.

One of the complicating factors here is that getValues() returns a two-dimensional array even though I am only pulling a single row of data (per the documentation ). I am not sure if I can create a 3D array somehow, and even if I can, whether that would be the best solution?

Thanks in advance for any help / thoughts / ideas!

When you get the values from a column, it's probably better to have a flat array [1,2,3] instead of [[1], [2], [3]] for future manipulations. This flattening can be achieved with

values.map(function (row) {return row[0]; });

As for storing values from multiple sheets, it's natural to use key-value pairs for that. That is, values will be a dictionary with keys being sheet names, and corresponding values the arrays of data from column A.

var sheetNames = ["Sheet1", "Sheet3", and "Sheet7"]
var ss = SpreadsheetApp.getActiveSpreadsheet();
var values = {};
for (var i = 0; i < sheetNames.length; i++) {
  var sheet = ss.getSheetByName(sheetNames[i]);
  values[sheetNames[i]] = sheet.getRange(2, 1, sheet.getLastRow()-1, 1)
                               .getValues()
                               .map(function (row) {
                                  return row[0];
                                });
}

These can be accesses later like values["Sheet1"][3] .

Displaying all sheets in one Dialog

Here's an example of how you can display the content of all sheets in one dialog by reading all of the data in all sheets via 3 nested loops.

The Code for All Sheets

function displayAllSheets() 
{
    var ss=SpreadsheetApp.getActive();
    var allshts=ss.getSheets();
    var s='<table>';
    for(var i=0;i<allshts.length;i++)//loop through all sheets
    {
      var sht=allshts[i];
      var rng=sht.getDataRange();//get all data in a sheet
      var valA=rng.getValues();
      for(var j=0;j<valA.length;j++)//loops through rows
      {
        s+='<tr>';
        if(j==0)
        {
          for(var k=0;k<valA[0].length;k++)
          {
            s+='<th>' + valA[j][k] + '</th>';
          } 
       }
       else
       {
          for(var k=0;k<valA[0].length;k++)
          {
            s+='<td>' + valA[j][k] + '</td>';
          }
        }
        s+='</tr>';
      }
    }
    s+='</table>';
    s+='<input type="button" value="Close" onClick="google.script.host.close();" />';
    var output=HtmlService.createHtmlOutput(s).setWidth(1000).setHeight(450);
    SpreadsheetApp.getUi().showModelessDialog(output, "All Sheets");
}

The Code with some sheets Excluded and Sheet Titles

function displayAllSheets() 
{
    var exclude=['set','tak','merge'];
    var ss=SpreadsheetApp.getActive();
    var allshts=ss.getSheets();
    var s='<table>';
    for(var i=0;i<allshts.length;i++)
    {
      var sht=allshts[i];
      if(exclude.indexOf(sht.getName())<0)
      {
        var rng=sht.getDataRange();
        var valA=rng.getValues();
        for(var j=0;j<valA.length;j++)
        {
          if(j==0){s+='<tr><th><strong>Sheet Name: ' + sht.getName() + '</strong></th></tr>';}
          s+='<tr>';
          if(j==0)
          {
            for(var k=0;k<valA[0].length;k++)
            {
                s+='<th>' + valA[j][k] + '</th>';
            }
          }
          else
          {
            for(var k=0;k<valA[0].length;k++)
            {
                s+='<td>' + valA[j][k] + '</td>';
            }
          }
          s+='</tr>';
        }
       }
    }
    s+='</table>';
    s+='<input type="button" value="Close" onClick="google.script.host.close();" />';
    var output=HtmlService.createHtmlOutput(s).setWidth(1000).setHeight(450);
    SpreadsheetApp.getUi().showModelessDialog(output, "All Sheets");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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