行总是返回 1 - Google Scripts

时间:2020-12-18 19:51:29

标签: javascript google-apps-script

我正在尝试使用电子表格中的值显示 HTML 页面。我点击我的生成 HTML 页面链接,它重定向到我创建的 HTML 页面。它显示正确,除了脚本总是从第一行获取值。我的印象是 doGet() 函数不接受行?可能是什么?

Code.gs

function fetchSpreadsheetValues(row) {
  var values = SpreadsheetApp.getActiveSheet().getRange(row, 1, row, 51).getValues(); // Get values from the specified range; original: row, 1, row, 51
  var rec = values[0];
  
  var candidate = {
    row: row, // always returning 1 (first row)
    r1: rec[0],
    r2: rec[1],
    r3: rec[2], 
    broker: rec[5], // Broker/Agent column
  };
  
  return candidate;
}
function doGet() { // must return HtmlOutput
  var cell = SpreadsheetApp.getActiveSheet().getCurrentCell(); // Get selected cell in the sheet
  var row = cell.getRow(); // Get selected cell's rows; always returning 1.
  
  var candidate = fetchSpreadsheetValues(row);
  
  var templ = HtmlService.createTemplateFromFile('agent-listing'); // Load HTML for the email; returns HtmlTemplate
  templ.candidate = candidate; // Assign candidate object to a variable in the template

  return templ.evaluate();
}

function onOpen() { // Add menu inside the spreadsheet
  var ui = SpreadsheetApp.getUi();
  ui.createMenu('Process').addItem('Send Email', 'showConfirmation').addItem('Generate HTML page', 'generateHTML').addToUi();
}

function generateHTML() {
  SpreadsheetApp.getUi()
  .showModalDialog(HtmlService.createHtmlOutputFromFile('openUrl').setHeight(50),"Generating HTML... Please wait.")
}

agent-listing.html

<!DOCTYPE html>
<html lang="en">
<head>
    <base target="_top">
    <meta charset="UTF-8">
    <title>Test</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <script>
      window.onload=function(){
        google.script.run.doGet();
      }
    </script>
</head>
<body>
  <div style="margin-left: 3%;">
    <!-- just to see the values -->
    <p>row <?= candidate.row ?>,</p>
    <p>R1 <?= candidate.r1 ?>,</p>
    <p>R2 <?= candidate.r2 ?>,</p>
    <p>R3 <?= candidate.r3 ?>,</p>
    <p>Hi <?= candidate.broker ?>,</p>
    <p>Test test</p>
  </div>
</body>
</html>

openUrl.html

<!DOCTYPE html>
<html>
  <head>
   <base target="_blank">
    <script>
     var url1 ='https://script.google.com/macros/s/AKfycbxU3VzpwPsBPEnfkPtMmCzo0YACc9UXPUlIcd6cm5Q/dev';
     var winRef = window.open(url1);
     winRef ? google.script.host.close() : window.alert('Allow popup to redirect you to '+url1) ;
     window.onload=function(){
       document.getElementById('url').href = url1;
     }
    </script>
  </head>
  <body>
    Kindly allow pop ups<br />or <a id='url'>click here</a> to continue!!!
  </body>
</html>

1 个答案:

答案 0 :(得分:1)

这是我如何完成两项工作以获取当前电子表格行和工作表。当我启动对话框时,我使用 getScriptUrl() 来获取当前的 scriptApp.getService().getUrl() 并且我还将行和工作表名称作为查询参数添加到 url。我计划在 doGet() 中使用它们,但在这个版本中我决定使用 cacheservice 将它们存储大约 30 秒,这足以启动 ah3,就像您的代理列表一样,dg() 函数使用它们获取活动工作表和当前行。

我只是尝试了 doGet(e) 和 dg(e) 使用 e.parameter.name 和 e.parameter.row 传递行和工作表名称,以便可以显示正确的数据,这也否定了需要在类似于您的 agent-listing.html 的“ah2.html”文件中调用 google.script.run.dg()。

我的 'ah3.html' 与您的 'openURL.html' 相似

<!DOCTYPE html>
<html>
<head>
    <base target="_blank">
    <script>
     window.onload=function(){
       google.script.run
       .withSuccessHandler(function(obj){
         var winRef = window.open(obj.url);
         winRef ? google.script.host.close() : window.alert('Allow popup to redirect you to '+ obj.url) ;
         document.getElementById('url').href = obj.url;
       })
       .getScriptUrl();
     }
    </script>
</head>

<body>
    Kindly allow pop ups<br />or <a id='url'>click here</a> to continue!!!
</body>

</html>

我的“ah3.html”和你的“agent-list.html”很相似

<!DOCTYPE html>
<html lang="en">
<head>
    <base target="_top">
    <meta charset="UTF-8">
    <title>Test</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <script>
      window.onload=function(){
        google.script.run.dg();//remove this if you use the query string in doGet(e)
      }
    </script>
</head>
<body>
  <div style="margin-left: 3%;">
    <!-- just to see the values -->
    <p>row <?= candidate.row ?>,</p>
    <p>R1 <?= candidate.r1 ?>,</p>
    <p>R2 <?= candidate.r2 ?>,</p>
    <p>R3 <?= candidate.r3 ?>,</p>
    <p>Hi <?= candidate.broker ?>,</p>
    <p>Sheet Name <?= sheet ?>,</p>
    
    <p>Test test</p>
  </div>
</body>
</html>

我的 ag3.gs 和你的 google 脚本代码很相似

function fetchSpreadsheetValues(row) {//this needs to be getting an obj with bow row and sheetname values  so if you decided to use cache service like I did then you'll need to modify this also.
  const ss=SpreadsheetApp.getActive();
  const sh=ss.getActiveSheet();
  const values=sh.getRange(row, 1, sh.getLastRow()-row+1, 51).getValues(); 
  const rec=values[0];
  var candidate={row: row,r1:rec[0],r2:rec[1],r3:rec[2],broker:rec[5]};
  return candidate;
}
function doGet(e) {
  return dg(e);
}

function launchDialog() {
  SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutputFromFile('ah3'),"Generating HTML... Please wait.");
}

function dg(e) {
  const ss=SpreadsheetApp.getActive();
  const cs=CacheService.getScriptCache();
  const sh=ss.getSheetByName(cs.get('name'));//use e.parameter.name here with querystring if you use them you can avoid the use of the cacheservice.
  var row=Number(cs.get('row'));//use e.parameter.row here with querystring
  var candidate=fetchSpreadsheetValues(row);
  var templ=HtmlService.createTemplateFromFile('ah2');
  templ.candidate=candidate;
  templ.sheet=sh.getName();
  return templ.evaluate();
}

function getScriptUrl() {
  const cs=CacheService.getScriptCache();
  const obj=getCurrentPosition();
  cs.put('row', obj.row, 30);
  cs.put('name', obj.name, 30);
  let robj={url:ScriptApp.getService().getUrl() + '?&row=' + obj.row + '&name=' + obj.name,row:obj.row,name:obj.name};
  Logger.log(JSON.stringify(robj));
  return robj;
}

function activesheettest() {
  const ss=SpreadsheetApp.getActive();
  const sh=ss.getActiveSheet();
  ss.toast(ss.getSheets()[0].getName());
}

function getCurrentPosition() {
  const ss=SpreadsheetApp.getActive();
  const sh=ss.getActiveSheet();
  const cell=sh.getActiveRange();
  const row=cell.getRow();
  const robj={row:row,name:sh.getName()};
  Logger.log(JSON.stringify(robj));
  return robj;
}

这是使用 webapp 查询字符串并将名称和行附加到 url 的版本。

ag3.gs:

function fetchSpreadsheetValues(obj) {
  const sheetname=obj.name;
  const row=obj.row;
  const ss=SpreadsheetApp.getActive();
  const sh=ss.getSheetByName(sheetname);
  const values=sh.getRange(row, 1, sh.getLastRow()-row+1, 51).getValues(); 
  const rec=values[0];
  var candidate={row: row,r1:rec[0],r2:rec[1],r3:rec[2],broker:rec[5]};
  return candidate;
}
function doGet(e) {
  return dg(e);
}

function launchDialog() {
  SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutputFromFile('ah3'),"Generating HTML... Please wait.");
}

function dg(e) {
  const ss=SpreadsheetApp.getActive();
  const cs=CacheService.getScriptCache();
  const sh=ss.getSheetByName(e.parameter.name);
  var row=Number(e.parameter.row);
  var candidate=fetchSpreadsheetValues({row:e.parameter.row,name:e.parameter.name});
  var templ=HtmlService.createTemplateFromFile('ah2');
  templ.candidate=candidate;
  templ.sheet=sh.getName();
  return templ.evaluate();
}

function getScriptUrl() {
  const cs=CacheService.getScriptCache();
  const obj=getCurrentPosition();
  cs.put('row', obj.row, 30);
  cs.put('name', obj.name, 30);
  let robj={url:ScriptApp.getService().getUrl() + '?&row=' + obj.row + '&name=' + obj.name,row:obj.row,name:obj.name};
  Logger.log(JSON.stringify(robj));
  return robj;
}

function activesheettest() {
  const ss=SpreadsheetApp.getActive();
  const sh=ss.getActiveSheet();
  ss.toast(ss.getSheets()[0].getName());
}

function getCurrentPosition() {
  const ss=SpreadsheetApp.getActive();
  const sh=ss.getActiveSheet();
  const cell=sh.getActiveRange();
  const row=cell.getRow();
  const robj={row:row,name:sh.getName()};
  Logger.log(JSON.stringify(robj));
  return robj;
}

ah2.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <base target="_top">
    <meta charset="UTF-8">
    <title>Test</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <script>
      window.onload=function(){
        //google.script.run.dg();
      }
    </script>
</head>
<body>
  <div style="margin-left: 3%;">
    <!-- just to see the values -->
    <p>row <?= candidate.row ?>,</p>
    <p>R1 <?= candidate.r1 ?>,</p>
    <p>R2 <?= candidate.r2 ?>,</p>
    <p>R3 <?= candidate.r3 ?>,</p>
    <p>Hi <?= candidate.broker ?>,</p>
    <p>Sheet Name <?= sheet ?>,</p>
    
    <p>Test test</p>
  </div>
</body>
</html>

ah3.html:

<!DOCTYPE html>
<html>
<head>
    <base target="_blank">
    <script>
     window.onload=function(){
       google.script.run
       .withSuccessHandler(function(obj){
         var winRef = window.open(obj.url);
         winRef ? google.script.host.close() : window.alert('Allow popup to redirect you to '+ obj.url) ;
         document.getElementById('url').href = obj.url;
       })
       .getScriptUrl();
     }
    </script>
</head>

<body>
    Kindly allow pop ups<br />or <a id='url'>click here</a> to continue!!!
</body>

</html>

我刚刚测试了这个版本,现在我修改了 fetchSpreadsheetValues() 函数,它可以正确获取数据。上面的版本可能仍然不正确,因为我没有修改那里的功能。