Home > Enterprise >  Why can't I get the search result using an app I made using Google App Script, even if I surely
Why can't I get the search result using an app I made using Google App Script, even if I surely

Time:09-08

By following the instruction of enter image description here

Components of the app

Data

A spreadsheet that contains the exactly same contents of the original spreadsheet (i.e. I copied the original contents and pasted them to my own spreadsheet to prepare the data)

Index.html

I copied the code from https://gist.github.com/bpwebs/dbbd96f8262e486c8f4c321ea0d3a95a#file-index-html and pasted it to 'Index.html' in my own GAS project.

Code.gs

I modified the original code on https://gist.github.com/bpwebs/dbbd96f8262e486c8f4c321ea0d3a95a#file-code-gs since the original code has an undefined variable (Sheets on ln.19) and cannot open the spreadsheet. I replaced the relevant code with SpreadsheetApp.openById() and range.getValues().

function doGet() {
  return HtmlService.createTemplateFromFile('Index').evaluate();
}
 
 
/* PROCESS FORM */
function processForm(formObject){  
  var result = "";
  if(formObject.searchtext){//Execute if form passes search text
      result = search(formObject.searchtext);
  }
  return result;
}
 
//SEARCH FOR MATCHED CONTENTS 
function search(searchtext){
  // var spreadsheetId   = '1p7fKVM7HA4Ikl8gYC2WesmHcIqAqJQWTfIuiqB4SyN4'; //** CHANGE !!!
  // var dataRage        = 'Data!A2:Y';                                    //** CHANGE !!!
  var ss = SpreadsheetApp.openById('The URL to my spreadsheet');
  var range = ss.getRange('Data!A2:Y');
  var data = range.getValues();
  // var data = Sheets.Spreadsheets.Values.get(spreadsheetId, dataRage).values;
  var ar = [];
   
  data.forEach(function(f) {
    if (~f.indexOf(searchtext)) {
      ar.push(f);
    }
  });
  return ar;
}

CodePudding user response:

Sheets API is used in the original code:

(See: Enable the Google Sheets API advanced service)

Sheets.Spreadsheets.Values.get(spreadsheetId, dataRage).values;

By default, the values are formatted and are strings.

(See: ValueRenderOption)


indexOf performs exact match on each element and the passed value, where the data type has to be the same.

Your are now using https://developers.google.com/apps-script/reference/spreadsheet/range#getvalues that unformatted values are returned (number as number and date as date object), which would always return false when indexOf() (exact match) is performed.

To get formatted values (string), use getDisplayValues().

  • Related