AppsScriptPulse

AI Tutor: Ben Explores Google AI Studio for a Glimpse into the Future of Google Sheets

Let’s see whether Google’s AI Studio can teach me how to build a pivot table in Google Sheets. It’s wild how fast this technology is progressing and this gives us a glimpse into the near future when we’ll all have personal AI assistants helping us work more efficiently.

In a recent YouTube video, Ben Collins, a prominent figure in the Google Sheets community, explored the capabilities of Google’s AI Studio by using it to guide him through the process of creating a pivot table. This experiment provides a compelling glimpse into the future of how we might interact with software, suggesting that AI could soon enable conversational, real-time interactions that go beyond the traditional user-driven model.

Ben began by logging into Google AI Studio and initiating a real-time screen share of his Google Sheet, which contained real estate data. He then engaged the AI assistant, powered by Gemini, to help him create a pivot table to analyze this data. The initial request was straightforward: to see the sum of sales prices broken down by property type. The AI assistant demonstrated an understanding of this request and provided step-by-step instructions. The AI correctly instructed Ben to start by selecting any cell within his data and then navigating to the Insert menu to select “Pivot table”.

The AI assistant did stumble initially, incorrectly stating that the pivot table option could be found under the Data menu. This highlights an important point: while impressive, AI assistants are not yet infallible. As Ben pointed out in the video, that could be a stumbling block if someone didn’t know to look under the Insert menu. Ben’s familiarity with Google Sheets allowed him to identify and correct the AI’s misstep, and continue with the tutorial. This shows that even with sophisticated AI tools, a foundational understanding of the software is still essential.

Once the pivot table was created, the AI guided Ben through adding “property type” to the rows and “sales price” to the values section. It also prompted Ben to ensure the summarization of sales price was set to “sum” instead of “count” or another option. This highlights the AI’s ability to understand the nuances of data analysis in Google Sheets and guide users to the correct settings. This is a key insight, because the AI isn’t just providing instructions but it is also understanding the data context.

Ben’s experiment provides a vision of a future where AI agents become sophisticated collaborators within Google Sheets. These agents would not only provide step-by-step instructions, but could also actively carry out tasks, such as reformatting tables or creating charts and graphs based on conversational prompts. Imagine, for example, saying “reformat this table to be more visually appealing” or “create a chart showing sales trends over time” and having the AI make those changes automatically. This would move beyond current user workflows which depend on menu clicks, or even hand-written Apps Scripts, and would allow users to focus on high-level goals and analysis, rather than the mechanics of the software.

It is clear from the video that Google AI is an important area to watch for the future of Google Workspace. However, even with AI integration, it is still important to understand the tools you are using to ensure the advice you are receiving is correct. This is an important point, as it shows that AI should be seen as a helpful assistant, not as a replacement for user understanding. If you are interested in reading more about this I recently published an article on Empowering Enterprise Productivity While Preserving Critical Thinking.

Source: Can AI teach me how to build a pivot table?

How to Use Google Apps Script to Auto-Label and Archive Gmail

Are you overwhelmed by a cluttered inbox? If you’re a power Gmail user, you may already know about the plus addressing feature that allows you to create custom email variations by appending a + and a label to your email address. For example, username+shopping@gmail.

Are you tired of sifting through a mountain of emails every day? Gmail’s “plus addressing” feature can be a lifesaver, and with a little Google Apps Script magic, you can transform it into a powerful automation solution.

If you are not familiar ‘plus addressing’ is a feature of Gmail which allows you to create custom variations of your email address by adding a “+” symbol and a label after your username, but before the “@” symbol. For instance, if your email is [email protected], you can use [email protected] for newsletters. While these emails still land in your main inbox, this subtle tweak opens the door to some clever automations using Google Apps Script.

This blog post, written by Senior Product Designer Niyas V, provides a step-by-step guide on using Google Apps Script to automatically label and archive emails based on the “plus addressing” variations. The script scans incoming emails, extracts the label after the “+”, applies the corresponding Gmail label, and then neatly archives the thread. The post includes the complete script, instructions on setting up a time-driven trigger for automation, and clear steps to save, authorise, and test your creation.

This tutorial is a fantastic resource for developers looking to learn practical Gmail automation using Google Apps Script and a great starting point if you are thinking about building other solutions using your inbox.

Source: How to Use Google Apps Script to Auto-Label and Archive Gmail

Unlocking Google Docs Content: A comprehensive guide to text extraction with Google Apps Script

4 Approaches to extracting the body text of a Google Doc with Google Apps Script. Full Code and tutorial

Scott Donald must be one of the most comprehensive Google Apps Script writers I know. All of his tutorials are packed with information and useful tips. This recent post is no exception, as Scott dives in and shares this detailed guide on retrieving a Google Docs body text using Google Apps Script.

The tutorial explores four approaches to extracting text from a Google Doc:

  1. DocumentApp: This approach is straightforward for basic text extraction but may not capture all elements, especially “Smart Chips.”
  2. DocumentApp with Element Iteration: This method allows for extracting text and URLs from standard text and supports some “Smart Chips” like Date, Rich Link, and Person.
  3. OCR Approach: This involves converting the document to a PDF, applying OCR, and reading the extracted text. It captures most displayed text but may not recognise emojis or some formula symbols.
  4. Docs API Advanced Service: This approach utilises the Docs REST API to access text, links, and specific “Smart Chip” data. It offers more control over data extraction but may require navigating complex JSON responses.

Scott’s tutorial provides a comprehensive and practical guide to retrieving Google Docs body text using Google Apps Script. Be sure to check out the full tutorial for detailed explanations, code examples, and helpful tips. And don’t forget to share your preferred approach and any challenges you’ve encountered on Scott’s post.

Source: Get a Google Docs Body Text with Apps Script – Yagisanatode

Google Apps Scripts for Google Workspace Administrators from The Awesome Script Site

Discover a treasure trove of scripts at The Awesome Script Site. Developed primarily for Google Workspace, these scripts offer solutions to common challenges faced by businesses and organizations. Created by Jonas Lund and soon other contributors, these scripts are free to use and come with comprehensive documentation. Share this resource with your network and remember to visit often for new additions.

The Awesome Script Site, by Jonas Lund, is a “treasure trove of scripts” for both users and Google Workspace administrators. The administrator scripts simplify various administrative tasks, but you will require a Google Workspace admin role to use them. Due to their handling of sensitive user data obviously please take time to review the scripts to make sure you are happy with how they work.

The scripts cover a wide range of functions, including:

  • Alias Management: Manage user email aliases directly from a Google Sheet.
  • Chromebook Reporting: Fetch and organize Chromebook data from your Google Workspace.
  • Group Member Management and Reporting: Bulk add or remove group members and generate group member reports.
  • OU Management: Create, list, and delete Organizational Units (OUs) based on specific criteria.

It’s worth spending a little time exploring the Awesome Scripts site to discover these admin scripts and more. To keep up-to-date on new ‘Awesome Scripts’ you can follow Jonas Lund on LinkedIn. Follow the source link to get the scripts and read more.

Source: The Awesome Script Site

Exporting and importing data between Google Sheets with Google Apps Script

When working with Google Sheets, you often use formulas like IMPORTRANGE to transfer data between files. However, IMPORTRANGE is not always reliable, especially when files become too large and you see the message “The file is too large.” In such cases, switching to a Google Apps Script-based solution that uses CSV files for data export and import is more efficient and flexible.

Here’s how you can create a system to export data from a Google Sheet to a CSV file and then import it into another sheet.


Export Data Script

This script exports data from a sheet named YOUR_TAB_NAME to a CSV file saved in Google Drive.

function exportToCSV() {
const SheetName = "YOUR_TAB_NAME";
const NameFile = "YOUR_FILE_NAME";

const ss = SpreadsheetApp.getActive();
const sourceSheet = ss.getSheetByName(SheetName);

  // Get the values ​​as displayed in the sheet
  const dataValues = sourceSheet.getDataRange().getDisplayValues();

  // Creating CSV content
  const csvContent = dataValues.map(row => row.join(";")).join("\n");

  // Check if there is data
  if(csvContent == "") return;

  try {
  
  const fileId = DriveApp.getFilesByName(NameFile + ".csv").next().getId();
        
        DriveApp.getFileById(fileId).setContent(csvContent);
  
  } catch {

        DriveApp.createFile(NameFile + ".csv", csvContent, MimeType.CSV);

  }
}

How It Works

  1. Fetches data from the specified sheet (YOUR_TAB_NAME).
  2. Creates CSV content, joining data with the ; separator.
  3. Updates the CSV file if it already exists or creates a new one.

Import Data Script

This script imports data from a CSV file into a Google Sheet named YOUR_TAB_NAME.

function importFromCSV() {
  const SheetName = "YOUR_TAB_NAME";
  const NameFile = "YOUR_FILE_NAME";
  const Separator = ";"; // Change your separator if needed

  const destinationSheet = SpreadsheetApp.getActive().getSheetByName(SheetName);

  let fileId;

  try {
    // Search for the file and get its ID
    fileId = DriveApp.getFilesByName(NameFile + ".csv").next().getId();
  } catch {
    Logger.log("Il file '" + NameFile + ".csv' non è stato trovato in Google Drive.");
    return;
  }

  const file = DriveApp.getFileById(fileId);
  const property = PropertiesService.getDocumentProperties();

  // Check if the last imported data has already been loaded
  const lastModified = property.getProperty("lastModified");

  const timeStamp = file.getLastUpdated().toUTCString();
  property.setProperty("lastModified", timeStamp);

  if (lastModified == timeStamp) return;

  // Retrieve the CSV content
  const csvContent = file.getBlob().getDataAsString();

  // Split the content into rows and then into columns using the specified separator
  const data = csvContent
          .split("\n") // Split into rows
              .map(row => row.split(Separator)); // Split each row into columns using the specified separator

  destinationSheet.clearContents();
  destinationSheet.getRange(1, 1, data.length, data[0].length).setValues(data);
}

How It Works

  1. Finds the CSV file in Google Drive.
  2. Checks for changes by comparing the file’s last modification time with a stored property value.
  3. Reads data from the CSV file and imports it into the sheet, clearing existing data first.

Automation with Triggers

To automate the import process, you can use a time-based trigger to run the script at regular intervals (e.g., every minute, hour, etc.).

Setting Up a Trigger

  1. Go to Apps Script Editor (Extensions > Apps Script).
  2. Click on Triggers (Clock icon) or Tools > Triggers in the editor.
  3. Create a new trigger:
    • Choose the importFromCSV function.
    • Select “Time-driven trigger.”
    • Specify the frequency (e.g., every minute).

With this trigger, your script will regularly check for updates in the CSV file and automatically import new data.


Explanation of the Separator Usage

Why the semicolon (;) is used: Descriptions or text fields may already use commas (,), and using them as a separator could lead to incorrect data splits. Using semicolons avoids this issue.

Alternative separator: If semicolons (;) are also present in the data, it’s recommended to use a unique symbol, such as §.

To update the separator, replace “;” with “§” in the following line:

.map(row => row.split("§")); // Update the separator here

This makes the script adaptable to various data scenarios.


Why Use This Method?

Advantages

  • Avoid IMPORTRANGE Limits: No errors related to overly large files.
  • Efficiency: Data is transferred as CSV, reducing connectivity issues between files.
  • Automation: Imports happen without manual intervention.

Limitations

  • Maintenance: Scripts need to be managed and updated manually if changes occur.
  • Security: Ensure file and script access is secure.

With these scripts and a configured trigger, you can reliably and efficiently handle large volumes of data between Google Sheets. If you need further customizations or help setting it up, feel free to ask!

Beginner’s guide to exponential backoff in Google Apps Script for handling rate limit errors

Exponential Backoff, a process by which when something fails you try again a set number of times whilst increasing the delay between each attempt.

Sample Apps Script code for Exponential Backoff

Sample Apps Script code for Exponential Backoff

The following Google Apps Script is designed to explore Exponential Backoff – a process by which when something fails you try again a set number of times whilst increasing the delay between each attempt, up to a certain point.

I needed this for a tool I built which adds Guests to a Calendar event from a Google Form submission. Whilst I was using ScriptLock to prevent simultaneous submissions, the code ran so fast that it would infrequently trip the Calendar API with the following error message “API call to calendar.events.patch failed with error: Rate Limit Exceeded”.

By infrequently I mean a reported issue only once in 3,500 submissions over the course of 12 months. Enough however to take the opportunity to learn about Exponential Backoff and to squash that single instance.

Just a note that this is one way to implement it.

Source: The Gift of Script: Exponential Backoff

Automate your Bluesky analytics with Google Apps Script and Sheets

Bluesky is gaining traction this end of 2024, and if you’re on the platform, you need to know your numbers. Want to track your Bluesky stats without the hassle? Google Apps Script and Google Sheets are here to rescue you with a simple, yet powerful solution.

In this blog post, Stéphane Giron provides a guide to tracking Bluesky social media statistics using Google Apps Script and Google Sheets. With the growing popularity of Bluesky it can be useful and interesting to understand the social media dynamic of the platform.

The script he offers tracks metrics such as the number of posts, followers, likes, reposts, and more. Stéphane also details how to install and set up the script, including copying and pasting the provided code, running initialization functions, and scheduling automatic data collection. The result is raw data that users can then use to create graphs and visualize their Bluesky activity over time.

Source: Bluesky Analytics, Track your Stats with Google Apps Script and Google Sheets

Going beyond the menu: Programmatic controlling Google Sheets protection using Google Apps Script

Google Apps Script automates tasks like managing protections in Google Spreadsheets. These protections control user access to specific cells. While scripts exist for this purpose, users still encounter challenges, prompting this report. The report aims to introduce techniques for managing protections using sample scripts, helping users understand and implement this functionality.

Google Sheets aficionados are likely no strangers to the “Protect sheet” and “Protect range” options tucked away in the menus. These features offer a basic level of control over who can edit what within your spreadsheet. But what if you need more dynamic, automated control over these protections? That’s where the power of Google Apps Script and the Sheets API comes into play.

This post from Kanshi Tanaike provides a deep dive into how you can programmatically manage protections in your Google Sheets. While the traditional menu options are great for static scenarios, using Google Apps Script allows you to create more flexible and powerful protection workflows.

Why Go Script?

  • Dynamic Protections: Instead of manually adjusting protections, you can use scripts to change them based on specific conditions or events within your spreadsheet.
  • Automation: Integrate protection changes into larger automation workflows, streamlining processes and reducing manual intervention.
  • Granular Control: Achieve a level of control over cell-level permissions that goes beyond the standard menu options.

Some possible use cases for developers could include:

  • Approvals Automation: Imagine a scenario where certain parts of a spreadsheet need to be locked down once a manager approves them. With this solution, you could create a script that automatically protects those ranges upon approval.
  • Time-Limited Editing: Need to open up a section of a spreadsheet for editing only during a specific window of time? You could use Google Apps Script to handle this, automatically protecting

The scripts provided by Kanshi Tanaike offer a starting point for exploring these possibilities.

Source: Technique for Protecting Google Spreadsheet using Google Apps Script

Google Apps Script: Mastering version control and deployment with CI/CD

Automate publication of your script from development to production easier.

This post by Stéphane Giron provides a CI/CD solution for Google Apps Script, which makes it easy for you to automate the deployment of Apps Script code from a development version to production. The solution uses the Apps Script API to manage versions and streamline the code copying process.

Stéphane has previously created a backup solution for Google Apps Script code, but it lacked version control and multi-file support. This new CI/CD solution addresses these limitations by using the Apps Script API to handle version management and the publication process.

The post includes the necessary code and configuration for implementing this solution. To use this solution you will need to enable the Apps Script API and as well as setting up your project with a standard Google Cloud Platform (GCP) Project.

As a bonus the solution also allows you the option of restoring previous versions of your deployed script, providing a rollback mechanism in case of errors or issues. This solution is lighter weight than other CI/CD setups featured in Pulse, but is easier to set up, providing a practical approach to implementing CI/CD for Google Apps Script projects and enhancing code management and deployment processes.

Source: Quick and not so dirty CI/CD solution for Google Apps Script | by Stéphane Giron | Oct, 2024 | Medium

Google Apps Script: The Secret to lightning-fast XML parsing with the Apps Script Engine (ASE)

I increased Apps Script’s performance 10x

Recently, I worked on a project with a client who needed to parse XML files and convert them to JSON. Simple enough, right? The catch? These XML files were massive — each containing hundreds or even thousands of trades. Naturally, the first thing I thought of was Google Apps Script’s built-in XMLService. It’s reliable, widely used, and integrates smoothly into Apps Script. But when I ran it on a file with 1,000 trades, the parsing took 45 seconds! That’s painfully slow for an automation process.

[Editor: In a recent blog post, Dmitry Kostyuk has shared a valuable tip for developers working with Google Apps Script. When faced with the task of parsing large XML files, he discovered that the built-in XMLService was causing significant slowdowns. For files containing thousands of records, the parsing process could take an agonizing 45 seconds.

Dmitry’s solution? Using his Apps Script Engine (ASE) and the xml-js NPM library. By making this switch, he was able to achieve a remarkable 10x increase in parsing speed, reducing the 45-second process to only 4 seconds.

If you’re working with Google Apps Script and large XML files, click the source post link to find out how you can give ASE and xml-js a try!]

Source: Make Apps Script Fast Again! With Apps Script Engine