简体   繁体   English

按钮操作,使用Google App脚本从电子表格中检索数据

[英]Button Action to retrieve data from spreadsheet using google app script

How to retrieve a complete row from a spreadsheet based on a filter on an action such as a click of a button. 如何基于对操作(例如单击按钮)的过滤器从电子表格中检索完整行。

I read that GAS is server-side scripting and it is complex to gain access to a spreadsheet. 我读到GAS是服务器端脚本,要访问电子表格很复杂。

Is that so. 是这样吗。 Please guide me. 请指导我。

I have done till this: 我已经做完了:

 $("#form-action")
    .button()
    .click(function() {

 var ss = SpreadsheetApp.openById("");
var sheet = SpreadsheetApp.getActiveSpreadsheet();
SpreadsheetApp.setActiveSheet(sheet.getSheetByName('Test'));
SpreadsheetApp.getActiveSheet().getRange("D1").setFormula('Query(A:C,"SELECT A,B,C WHERE B="' + "mydata'" + ',1)'); 
SpreadsheetApp.getActiveSheet().getRange("E:J").getValues();

});

Gaining access to the spreadsheet is not difficult at all. 完全可以访问电子表格。 You have to remember that while Google Apps Script runs on Google servers, the client-side code (eg HTML and JavaScript code you use in your UI templates) will be sent to your browser for rendering, so you can't really mix the two and write jQuery code in GAS(.gs) files or vice versa. 您必须记住,虽然Google Apps脚本在Google服务器上运行,但是客户端代码(例如,您在UI模板中使用的HTML和JavaScript代码)将发送到浏览器进行渲染,因此您无法真正将两者混用并在GAS(.gs)文件中编写jQuery代码,反之亦然。

To clarify, commands like 为了澄清,命令如

 var ss = SpreadsheetApp.openById("");

must be kept in .gs files. 必须保存在.gs文件中。 To use client-side HTML and JavaScript, you must create separate HTML files in your project (go to File - New - HTML file). 要使用客户端HTML和JavaScript,必须在项目中创建单独的HTML文件(转到文件-新建-HTML文件)。 Here's more information on serving HTML in GAS https://developers.google.com/apps-script/guides/html/ 这是有关在GAS中提供HTML的更多信息https://developers.google.com/apps-script/guides/html/

Luckily, Google provides the API that allows you to communicate between client and server sides by calling 'google.script.run.' 幸运的是,Google提供了API,通过调用“ google.script.run”,您可以在客户端和服务器端之间进行通信。 followed by the name of the function in '.gs' file. 后跟“ .gs”文件中的函数名称。

Example function in '.gs' file .gs文件中的示例函数

function addRow() {

var sheet = SpreadsheetApp.getActive()
                          .getSheets()[0];

sheet.appendRow(['Calling', 'server', 'function']);

}

In your HTML template file, here's how you would call this function 在HTML模板文件中,这是调用此函数的方式

<script>
    google.script.run.addRow();
</script>

Consider the example that is more relevant to your situation. 考虑与您的情况更相关的示例。 In my spreadsheet, the QUERY formula changes dynamically based on the value entered by the user. 在我的电子表格中,QUERY公式根据用户输入的值动态变化。 The form with input field is displayed in the sidebar. 带有输入字段的表单显示在侧栏中。

在此处输入图片说明

Project structure 项目结构

在此处输入图片说明

Code for 'sidebar.html' is below. “ sidebar.html”的代码如下。 Note that using the 'name' attribute of the <input> element is mandatory. 请注意,必须使用<input>元素的'name'属性。 On form submit, the value of the attribute ('filterBy') will be transformed into propetry of the form object that we can reference in our server function to get user input. 在提交表单时,属性的值('filterBy')将转换为表单对象的属性,我们可以在服务器功能中引用该表单对象以获取用户输入。

    <!DOCTYPE html>
    <html>
      <head>
        <base target="_top">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
      </head>
      <body>
        <form id="myForm">

        <input type="text" name="filterBy">

        <input type="submit" value="submit">

        </form>

        <table id="myTable"></table>

        <script>

        $('document').ready(function(){

         var form = $('#myForm');
         var table = $('#myTable');
         var runner = google.script.run;

         form.on('submit', function(event){

            event.preventDefault(); //prevents <form> redirecting to another page on submit
            table.empty(); // clear the table

            runner.withSuccessHandler(function(array){ //this callback function will be invoked after the 'retriveValues()' function below

            for (var i = 0; i < array.length; i++) {

             var item = '<tr><td>' + array[i] +'</td></tr>';
             table.append(item);


            }


            })
               .retrieveValues(this); //the function that will be called first. Here, 'this' refers to the form element


         });



        });


        </script>
      </body>
    </html>

Code in '.gs' file: “ .gs”文件中的代码:

var ss = SpreadsheetApp.getActive();
var sheet = ss.getSheets()[0];


function onOpen() {

var ui = SpreadsheetApp.getUi();
var htmlOutput = HtmlService.createTemplateFromFile('sidebar')
                          .evaluate();

ui.showSidebar(htmlOutput);

}


function retrieveValues(req) {

var res = [];  
var filterBy = req.filterBy; //getting the value of the input field. 

sheet.getRange(1, 2, 1, 1)
     .setFormula("QUERY(A1:A, \"SELECT A WHERE A > " + filterBy + "\")");


sheet.getRange(1, 2, sheet.getLastRow(), 1)
     .getValues()
     .map(function(value){

                     if (value[0] != "") res = res.concat(value[0]); // get only the values that are not empty strings. 

                  });

return res;  


}

Here's the result of entering the value and submitting the form. 这是输入值并提交表单的结果。 The server-side function returns the array of values greater than 5. The callback function that we passed as parameter to 'withSuccessHandler' then receives this array and populates the table in the sidebar. 服务器端函数返回值大于5的数组。我们作为参数传递给'withSuccessHandler'的回调函数然后接收该数组并在边栏中填充表。

在此处输入图片说明

Finally, I'm not sure why you are using the QUERY formula. 最后,我不确定为什么要使用QUERY公式。 Instead of modifying 'SELECT' statement, you could simply take the values from the target range an filter them in GAS. 无需修改“ SELECT”语句,您可以简单地从目标范围中获取值并在GAS中对其进行过滤。

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

相关问题 使用Google Apps脚本作为服务从电子表格中检索数据 - Using Google Apps Script as service to retrieve data from spreadsheet 如何从电子表格中检索图表Google脚本的数据。 (使用HTML服务) - How to retrieve data from spreadsheet for chart google script. (Using HTML Service) 使用Google脚本将数据从一个Google电子表格拉到另一电子表格 - Pull data from one Google spreadsheet to another using Google script 在谷歌电子表格中存储/检索数据 - Store/retrieve data to/from a google spreadsheet 在谷歌应用脚本中的电子表格中写入数据 - Writing data in spreadsheet in google app script Google App脚本电子表格 - Google App Script Spreadsheet 使用应用脚本将Google电子表格数据导入Google表单 - Import google spreadsheet data into google forms with app script 如何使用Google App脚本中的JavaScript从Google电子表格数据库中获取日期值 - How do i get the date value from google spreadsheet database using javascript in google app script 如何在不使用电子表格 ID 的情况下使用 Google 脚本从另一个 Google 表格导入数据 - How to import data from another Google Sheet using Google Script without using Spreadsheet ID 使用HTTP GET和Google App脚本访问Google电子表格的标题 - Accessing headers of a google spreadsheet using HTTP GET and Google App Script
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM