Imtiaz
Imtiaz

Reputation: 153

Search column and display row

I need to publish individual's exam result from this google sheet. Spreadsheet. I've found a code that can do this if I run the app URL with "?id=1" like but it displays only the name. I need to show the marks (Column C to G) also. The code I used is

var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1L1Qu6QCaDucr4Jy5eOAnQkX-wpYjz6eevqAMzBc72iQ/edit#gid=0");
var sheet = ss.getSheetByName("Sheet1");

function doGet(e){
 return search(e) ;
}  

function doPost(e){
 return search(e) ;
}  


function search(e){
 var id = e.parameter.id;
  
  var values = sheet.getRange(2, 1, sheet.getLastRow(),sheet.getLastColumn()).getValues();
  
  for(var i = 0;i<values.length; i++){
    
    if(values[i][0] == id ){
      i=i+2;
      
      var name = sheet.getRange(i,3).getValue();
      return ContentService.createTextOutput(name).setMimeType(ContentService.MimeType.TEXT);
    }
  }
  return ContentService.createTextOutput("Id not found").setMimeType(ContentService.MimeType.TEXT);
  
}

How can I show the whole row instead of a single cell?

Upvotes: 0

Views: 84

Answers (1)

oshliaer
oshliaer

Reputation: 4969

This works for me like a charm

/**
 *
 * @param {*} e
 */
function search(e) {
  var id = e.parameter.id;

  var values = sheet
    .getDataRange()
    .getValues()
    .filter(function(row) {
      return row[0] == id;
    });

  var content = JSON.stringify(values);
  return ContentService.createTextOutput(content).setMimeType(
    ContentService.MimeType.TEXT
  );
}

I can expand the sheet as I need and I don't need charge the script at the same time

If you expect to return "Id not found" try

var content = values.length ? JSON.stringify(values) : "Id not found";

instead.

Upvotes: 1

Related Questions