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?

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!

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

Quickly copy or move existing files in Google Drive from a Google Sheet

Quickly copy or move existing files into folders within Google drive via a Google Sheet.

Quickly copy or move existing files into folders via a Google Sheet

Quickly copy or move existing files into folders via a Google Sheet

The following Google Apps Script tool allows you to quickly copy or move existing files into existing folders within Google/Shared drive. This is quite a niche tool so it is anticipated you would already have a Google Sheet of file IDs/URLs, though there is the option to select an existing Drive folder of files and automatically bring them into this tool.

You can continue to append further rows to the Google Sheet as existing ones will be skipped once the ā€˜Statusā€™ column has automatically been marked as ā€˜Completedā€™. Alternatively you can clear the Sheet each time for a fresh start.

Source: The Gift of Script: Copy or move file into folder Tool

Quickly append file permissions in Google Drive with Google Sheets and Google Apps Script

Quickly append new permissions to existing files within Google Drive. Insert email addresses using a comma-space format with optional notifications.

Quickly append new file permissions via a Google Sheet

The following Google Apps Script tool allows you to quickly append new permissions to existing files within Google/Shared drive. This is quite a niche tool so it is anticipated you would already have a Google Sheet of file IDs/URLs, though there is the option to select an existing Drive folder of files and automatically bring them into this tool.

By inserting email addresses using a comma-and-space format you can optionally select to send a notification email to the new user(s)

You can continue to append further rows to the Google Sheet as existing ones will be skipped once the ā€˜Statusā€™ column has automatically been marked as ā€˜Completedā€™. Alternatively you can clear the Sheet each time for a fresh start.

Source: The Gift of Script: Append Drive file permissions Tool

Effortlessly integrate WooCommerce customer data in Google Sheets with a little Google Apps Script

Learn how to easily export your WooCommerce customers email, name and address to Google Sheets using Google Apps Script. The script will create a new tab in your Google Sheet and copy the data from the WooCommerce customers table.

If you are a WooCommerce store owner you might be interested in this solution by Amit Agarwal who provides a step-by-step guide on how to export WooCommerce customer data (email, name, address) to Google Sheets using Google Apps Script.

No more manual CSV exports or complex integrations, simply copy the provided script and follow the setup instructions. With this solution you can enhance your workflows, gain insights, and enhance your customer outreach. If you are not an existing WooCommerce user a solution for developers to keep in mind if you are seeking to optimise your Google Workspace add-ons customer experience.

Source: How to Export WooCommerce Customers to Google Sheets – Digital Inspiration

Unlock the power of charts: Get your free Google Sheets visual vocabulary template from Ben CollinsĀ 

Enhance your Google Sheets skills with this Visual Vocabulary template. Learn how to choose the right charts, create effective visualizations, and design professional-looking dashboards. This comprehensive guide includes 31 common chart types, tips for data organization, and step-by-step instructions for using the SUBTOTAL formula to create interactive “Show/Hide” rows. Perfect for data enthusiasts and spreadsheet users of all levels!

Friend and fellow GDE, Ben Collins, has recently announced a new ā€˜Sheets Insidersā€™ membership program where heā€™ll be sharing some exclusive members-only newsletters, new templates, deep-dive tutorials, and more for both Google Sheets and Apps Script.

If you would like to ā€˜try before you buyā€™ Ben has shared the first issue of the Sheets Insiders membership program, featuring a Visual Vocabulary template for Google Sheets. The template is designed to help you in chart selection and the accompanying videos include lots of great tips to help you cleanly format your spreadsheets.

Future Sheets Insiders issues will delve into chart tricks, dropdown menus, interactive elements, AI and Sheets integration, formula challenges, and Apps Script content. The newsletter content will be archived in the Sheets Insiders Content Library for future reference. Click through to read more about Sheets Insiders and get your copy of the Google Sheets Visual Vocabulary Template.

Source: Sheets Insiders 1: Visual Vocabulary Template

Check comma separated email address is valid

Loop through a Google Sheet cell of comma-space separated email addresses and check their format is valid, otherwise display a user popup.

The following Google Apps Script is designed to loop through a Google Sheet cell of email addresses that have been separated by a comma and space. It then uses a regular expression (regex) to confirm the email address meets the correct formatting criteria.

This code was developed as a way of implementing additional checks when asking users to be precise in how exactly they enter multiple email addresses. So if they were to forget theĀ spaceĀ for instance it could alert them, before the rest of the code risked failing as whatever task it was designed to do.

Source: The Gift of Script: Check comma separated email address is valid

Using Google Forms and the Gemini API to automate creation of multiple choice questions (MCQs)

This report proposes a novel learning method using Gemini to automate Q&A generation, addressing the challenges of manual Q&A creation. By integrating with Google tools, this approach aims to enhance learning efficiency, accessibility, and personalization while reducing costs.

The rapid advancement of technology has offered both opportunities and challenges to the education sector. While technology can be a valuable tool for supporting teaching and learning, concerns about its appropriate use have existed for a long time.

The education sector is witnessing an increase in AI tools, each promising to enhance teaching and learning. However, the quality of these tools varies significantly. Some are better designed and can – if used appropriately – can be beneficial, while others are poorly designed. This can make it challenging for educators to find the right solutions that meet their specific needs.

This blog post by Kanshi Tanaike sheds light on the inner workings of some commercial AI tools developed for educators. It demonstrates how these tools can use generative AI to create multiple-choice questions (MCQs) on a given topic. In this particular solution, Google Forms are used in the process, with questions and answers automatically generated by the Gemini API for the user to answer in a Google Form.

For educators who have experience with Google Apps Script, this project looks like a useful starting point to refine and create your own solution or simply used to gain insights into the functioning of similar commercial tools.

Source: A Novel Approach to Learning: Combining Gemini with Google Apps Script for Automated Q&A