简体   繁体   English

在GAS中,通过循环读取电子表格中多个工作表中的数据列

[英]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. 我正在尝试从电子表格中的多个工作表中的GAS(Google Apps脚本)中读取数据,但无法确定如何执行此操作。

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: 在此示例中,我们假设我关心的3个工作表的名称存储在数组中:

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. 第一列A列包含唯一ID,其余列包含其余数据。

So for instance, the Sheet1 looks like this: 因此,例如,Sheet1看起来像这样: 在此处输入图片说明

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. 我的目标:我试图从Sheet1,Sheet3和Sheet7中的每一个中读取列A中的ID列,并存储该数据以备后用。

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. 到目前为止,我所遇到的问题(当然是:))是通过循环的每次迭代都覆盖了变量values 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. 我想做的是将数组归类为数组,以便values[0]包含一个来自Sheet1的A列的数组, values[1]包含一个来自Sheet3的A列的数组,等等。

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 ). 这里最复杂的因素之一是,即使我仅提取一行数据(根据文档 ), getValues()也会返回二维数组。 I am not sure if I can create a 3D array somehow, and even if I can, whether that would be the best solution? 我不确定是否可以以某种方式创建3D阵列,即使可以,这是否是最佳解决方案?

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. 从列中获取值时,最好使用平面数组[1,2,3]而不是[[1], [2], [3]]以便将来进行操作。 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. 也就是说, values将是一个字典,键是工作表名称,而对应的值将是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] . 以后可以像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. 这是一个示例,说明如何通过3个嵌套循环读取所有工作表中的所有数据,从而在一个对话框中显示所有工作表的内容。

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");
}

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

相关问题 通过GAS将数字符号(#)插入Google电子表格 - Insertion of number sign (#) into a Google Spreadsheet via GAS 我无法通过 GAS 将部分数据从 chrome 扩展发送到电子表格 - I cannot send a part of data from chrome extension to Spreadsheet via GAS 如何基于单个单元格编辑(Google Script / GAS)通过电子邮件发送电子表格中的整行数据 - How to send whole row of data in my spreadsheet via email based on single cell edit (Google Script / GAS) GAS:从电子表格数据填充下拉列表 - GAS: Populating a dropdown list from Spreadsheet data 使用GAS从/向电子表格读取和写入时间值 - Reading and writing time values from/to a spreadsheet using GAS GAS:将 Google Drive 中多个 Google Sheets 文档(工作簿)中的数据合并到一个工作簿中 - GAS: Combine Data from Multiple Google Sheets Documents (Workbooks) in Google Drive into One Workbook 电子表格服务:读取数据 - Spreadsheet Service: Reading Data 如何检查谷歌电子表格中的输入数据是否是 GAS 的有效日期类型 - how to check if the input data in google spreadsheet is a valid Date type by GAS 将数据推送到不同的元素,具体取决于使用 GAS 的谷歌电子表格中的列? - Push data to different elements, depending on column in google spreadsheet with GAS? GAS scriplet用于创建包含电子表格数据链接的HTML列 - GAS scriplet to create an HTML column with links from spreadsheet data
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM