Get second, third and so on values

时间:2017-08-05 11:10:01

标签: javascript arrays google-apps-script google-sheets google-apps

I have this problem here

The problem has been solved, but my question is how can I get the second value from that, or the third one. The sheet will have many tables and at some point I will need a total for each table. Also, is there any solution to automatically find the the array number which contain date row for each table (instead defining this manually). Hope my explanation make sense.

Thank you!

Kind regards,

L.E. Test file

1 个答案:

答案 0 :(得分:2)

如果我理解你的问题,而不是在找到与“总计”匹配时打破循环,那么在循环中需要做的事情就像这样......

var today = toDateFormat(new Date());
var todaysColumn = 
    values[5].map(toDateFormat).map(Number).indexOf(+today);
var emailDate = Utilities.formatDate(new Date(today),"GMT+1", 
                                     "dd/MM/yyyy");
for (var i=0; i<values.length; i++){
  if (values[i][0]=='Total'){
    nr = i;
    Logger.log(nr); 

    var output = values[nr][todaysColumn];
    //     Do something with the output here I"m assuming you email it

  }
}

循环将继续并找到每个“Total”并执行相同的操作。这个答案假设“总计”在同一列中。如果您只想要发送某些表而不是其他表,那么您可以更好地使用此功能,但这应该可以让您入门。

我不太明白你问题的第二部分......

  

“此外,是否有任何解决方案可以自动找到该阵列   包含每个表的日期行的数字(而不是定义它   手动地)。希望我的解释有意义。“

我猜你想要特定列中包含“Total”的所有行。您可以将变量实例化为空数组,如var totals = [];。然后,不是在第一个循环中发送电子邮件或其他内容,而是将行值推送到数组,如totals.push(nr+1) . //adding 1 gives you the actual row number (rows count from 1 but arrays count from 0)。然后,您可以简单地遍历总数数组并执行您想要执行的任何操作。或者,您可以创建一个包含所有值的数组,而不是像totals.push(values[nr][todaysColumn])那样的行号,并循环遍历该数组。有很多方法可以解决这个问题!

根据我们在下面的对话,我编辑了“测试”表并更新了代码。以下是我的修改

所有修改都已在您的测试表中进行,并在Logger中进行了验证。如果您有任何问题,请告诉我。

<强>电子表格

  1. 添加了“验证”标签
  2. 编辑了“表格”标签,因此A列中带有“电子邮件地址”的行与所需的查找值(日期或类别)对齐...这仅适用于前两个表,因为所有其他表已经具有此条件
  3. <强>代码: 创建表/类别选择器...

    1. 在编辑器中转到文件&gt;&gt;新&gt;&gt; HTMLFILE
    2. 将文件命名为“inputHTML”
    3. 将以下代码复制并粘贴到该文件中
    4. <!DOCTYPE html>
      <html>
         <head>
            <base target="_top">
         </head>
         <body>
            <form class="notice_form" autocomplete="off" onsubmit="formSubmit(this)" target="hidden_iframe">
               <select id="tables" onchange="hideunhideCatagory(this.value)" required></select>
               <p></p>
               <select id="categories" style="display:none"></select>
               <hr/>
               <button class="submit" type="submit">Get Total</button>
            </form>
            <script>
               window.addEventListener('load', function() {
               console.log('Page is loaded');
               });
            </script>
            <script
               src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
            <script type="text/javascript">
               // The code in this function runs when the page is loaded.
               $(function() {
               var tableRunner = google.script.run.withSuccessHandler(buildTableList);
               var catagoryRunner = google.script.run.withSuccessHandler(buildCatagoryList);
                 
                 tableRunner.getTables();
                 catagoryRunner.getCategories();
               });
               
               function buildTableList(tables) {
               var list = $('#tables');
               list.empty();
               list.append('<option></option>');
               for (var i = 0; i < tables.length; i++) {
               if(tables[i]==''){break;}
               list.append('<option>' + tables[i] + '</option>');
               }
               }
               
               function buildCatagoryList(categories) {
               var list = $('#categories');
               list.empty();
               list.append('<option></option>');
               for (var i = 0; i < categories.length; i++) {
               if(categories[i]==''){break;}
               list.append('<option>' + categories[i] + '</option>');
               }
               }
               
               function hideunhideCatagory(tableValue){
               var catElem = document.getElementById("categories");
               if(tableValue == "Total Calls By Date" || tableValue == "Total Appointments by Date"){
               catElem.style.display = "none"
               document.required = false;
               }else{
               catElem.style.display = "block"
               document.required = true;
               }
               
               }
               
               function formSubmit(argTheFormElement) {
               
               var table = $("select[id=tables]").val(),
                 catagory = $("select[id=categories]").val();
               console.log(table)
               google.script.run
               .withSuccessHandler(google.script.host.close)
               .getTotal(table,catagory);
               }
            </script>
         </body>
         <div id="hiframe" style="display:block; visibility:hidden; float:right"> 
            <iframe name="hidden_iframe" height="0px" width="0px" ></iframe>
         </div>
      </html>

      编辑Code.gs文件 用这个替换Code.gs中的代码......

      //This is a simple trigger that creates the menu item in your sheet
      function onOpen() {
        var ui = SpreadsheetApp.getUi();
        ui.createMenu('Run Scripts Manually')
        .addItem('Get Total','fncOpenMyDialog')
        .addToUi();
      
      }
      //This function launches the dialog and is launched by the menu item
      function fncOpenMyDialog() {
        //Open a dialog
        var htmlDlg = HtmlService.createHtmlOutputFromFile('inputHTML')
            .setSandboxMode(HtmlService.SandboxMode.IFRAME)
            .setWidth(200)
            .setHeight(150);
        SpreadsheetApp.getUi()
            .showModalDialog(htmlDlg, 'Select table to get total for');
      };
      
      
      //main function called by clicking "Get Total" on the dialogue...variables are passed to this function from the formSubmit in the inputHTML javascript
      function getTotal(table,catagory) {
        function toDateFormat(date) {
          try {return date.setHours(0,0,0,0);}
          catch(e) {return;}
        }
      
        //get all values
        var values = SpreadsheetApp
        .openById("10pB0jDPG8HYolECQ3eg1lrOFjXQ6JRFwQ-llvdE2yuM")
        .getSheetByName("Tables")
        .getDataRange()
        .getValues();
      
        //declare/instantiate your variables
        var tableHeaderRow, totalRow, tableFound = false;
        //begin loop through column A in Tables Sheet
        for (var i = 0; i<values.length; i++){
          //test to see if values have already been found if so break the loop
          if(tableFound == true){break;}
          //check to see if value matches selected table
          if (values[i][0]==table){
            //start another loop immediately after the match row
            for(var x=i+1; x<values.length; x++){
              if(values[x][0] == "Email Address"){ //This header needs to consistantly denote the row that contains the headers
                tableHeaderRow = x;
                tableFound = true;
              }else if(values[x][0] == "Total"){
                totalRow = x;
                break;
              }
            }
          }
        }
      
        Logger.log("Header Row = "+tableHeaderRow)
        Logger.log("Total Row = "+ totalRow)
        var today = toDateFormat(new Date())
        var columnToTotal;
        if(catagory==''){
          columnToTotal = values[tableHeaderRow].map(toDateFormat).map(Number).indexOf(+today);
        }else{
          columnToTotal = values[tableHeaderRow].indexOf(catagory);
        }
      
        var output = values[totalRow][columnToTotal];
        Logger.log(output);
        var emailDate = Utilities.formatDate(new Date(today),"GMT+1", "dd/MM/yyyy");
      
        //here is where you would put your code to do something with the output
      
      }
      
      /** The functions below are used by the form to populate the selects **/
      function getTables(){
        var cFile = SpreadsheetApp.getActive();
        var cSheet = cFile.getSheetByName('Validation');
        var cSheetHeader = cSheet.getRange(1,1,cSheet.getLastRow(),cSheet.getLastColumn()).getValues().shift();
        var tabelCol = (cSheetHeader.indexOf("Tables")+1);
        var tables = cSheet.getRange(2,tabelCol,cSheet.getLastRow(),1).getValues();
        return tables.filter(function (elem){
          return elem != "";
        });
      }
      
      function getCatagories(){
        var cFile = SpreadsheetApp.getActive();
        var cSheet = cFile.getSheetByName('Validation');
        var cSheetHeader = cSheet.getRange(1,1,cSheet.getLastRow(),cSheet.getLastColumn()).getValues().shift();
        var catagoriesCol = (cSheetHeader.indexOf("Catagory")+1);
        var catagories = cSheet.getRange(2,catagoriesCol,cSheet.getLastRow(),1).getValues();
        return catagories.filter(function (elem){
          return elem != "";
        });
      }