Search code examples
google-docs

How to sum values in rows in a table in Google Docs?


i have a table of different prices in each rows. how do i make a sum of those rows in google docs and display it with "sum="?

Unit Name Description Price <> <> <> <> <> <>

sum=


Solution

  • I found this script and tested it.

    function sumTable() {
      var doc = DocumentApp.getActiveDocument();
        var body = doc.getBody();
    
      var tables = body.getTables();
        var numRows = tables[0].getNumRows();//specify the table in [ ] that you're working with
    
      var row;
        var val;
      var total = 0.0;
        for(row = 1; row<numRows-1; row++) {
            val = tables[0].getCell(row, 2).getText();
           
        if(val) {
            total += parseFloat(val);
            }
      }
    
      tables[0].getCell(numRows -1,2).setText("$"+total.toString());
    }
    

    Now when you click “Run” in your Apps Script project it will execute and update the table, if you want to run the script from the Google Doc, you can run this other function and it will add an option under “Add-ons” from the Google Doc menu.

    function onOpen(e) {
        var menu = DocumentApp.getUi().createAddonMenu();
        menu.addItem("Sum Table", "sumTable");
        menu.addToUi();
    }