Simple Google Apps Script Sheet Addon Code snippet

Google Apps Script add-ons are a type of script that extends the functionality of Google Docs, Sheets, and Forms. They are created using Google Apps Script and can be published and shared with other users.

Here’s an example of a Google Apps Script add-on code:

function onOpen() {
var ui = SpreadsheetApp.getUi();
var menu = ui.createMenu(‘My Custom Menu’);
menu.addItem(‘Launch’, ‘showSidebar’)
.addToUi();
}

function showSidebar() {
var html = HtmlService.createHtmlOutputFromFile(‘sidebar’)
.setTitle(‘My Addon’)
.setWidth(300);
SpreadsheetApp.getUi()
.showSidebar(html);
}

function getData() {
var sheet = SpreadsheetApp.getActiveSheet();
var data = sheet.getDataRange().getValues();
return data;
}

The onOpen() function creates an add-on menu in the Google Sheets toolbar with a single item that says “Launch”. When the item is clicked, it runs the showSidebar() function.
The showSidebar() function creates a new HTML sidebar and displays it in the Google Sheets sidebar. The HTML is defined in a separate file called “Sidebar.html”. The sidebar has a title of “My Addon” and a width of 300 pixels.
The getData() function retrieves the data from the active sheet in the spreadsheet and returns it as a two-dimensional array.
When the user clicks on the “Launch” menu item in the add-on menu, the showSidebar() function is called, which creates a new sidebar with the specified HTML content. The user can interact with the sidebar and it can call any of the other functions defined in the script, such as getData().

Code for sidebar.html

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>
    <div>
      <h1>My Addon Sidebar</h1>
      <p>Click the button to get data from the active sheet.</p>
      <button onclick="getData()">Get Data</button>
    </div>
    
    <script>
      function getData() {
        google.script.run.withSuccessHandler(displayData).getData();
      }
      
      function displayData(data) {
        var output = '';
        for (var i = 0; i < data.length; i++) {
          output += data[i].join('\t') + '<br>';
        }
        document.getElementById('output').innerHTML = output;
      }
    </script>
    
    <div id="output"></div>
  </body>
</html>