Home > Software design >  send html table data to google sheet via apps-script
send html table data to google sheet via apps-script

Time:02-14

trying to get the cell values from html table and send them to google sheet via apps script:

index.html:

     var values = [];
     $("td").each(function(){
       values.push($(this).text());
     });
      
alert(values);  // i can see the array in the alert.

      google.script.run.addRows(values);
    }

code.gs:

function addRows(values) {
  
  var doc = SpreadsheetApp.openById("id");
  var sheet = doc.getSheetByName('newdata');
  var lastrow = sheet.getLastRow();
   sheet.getRange(lastrow 1, 1, values.length, values[0].length).setValues(values);
}

i got an error in the console uncaught addRows, it seems that the array is not detected on the server side, can anyone help thanks in advance

CodePudding user response:

This works well for me

gs:

function showSidebar() {
  const html = HtmlService.createTemplateFromFile('index');
  var evaluatHTML = html.evaluate().setTitle('Sidebar')
  SpreadsheetApp.getUi().showSidebar(evaluatHTML)
};

function addRows(values) {
  Browser.msgBox(values)
}

html:

  <script>
    function ok(){
     var values = [];
     $("td").each(function(){
       values.push($(this).text());
     });
      
      alert(values);  // i can see the array in the alert.

      google.script.run.addRows(values);
    }
  </script>

note that you have to transform the result in a 2D Array, for instance

function addRows(values) {
  var tab = [values]
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet()
  sheet.getRange(1, 1, tab.length, tab[0].length).setValues(tab)
}

CodePudding user response:

 var values = [];
 $("td").each(function(){
   values.push($(this).text());
 });
 var finalarray =  [[values]]

// this will be a 1 row to append

  • Related