Google Sheets Script to Report Data: A Full Guide
In this article
To report data using a Google Sheets script, you use Google Apps Script (GAS), a JavaScript-based platform that allows you to automate data collection, summarize figures, and send them via email or to another sheet. By writing a custom function, you can tell Google Sheets to look at a specific range of cells, calculate a total or filter for specific criteria, and then trigger a notification or a new report generation based on a schedule or a button click.
What You'll Need
- A Google Account with access to Google Sheets.
- A dataset within a Google Sheet (this can be manual entries or data imported from an external API).
- Basic familiarity with JavaScript (though you can copy and adapt the logic provided here).
- A destination for your report (e.g., an email address or a secondary "Summary" tab within the same spreadsheet).
Step-by-Step
- Prepare Your Data Source: Ensure your data is organized in a clean table format. For this guide, assume you have a sheet named "SalesData" where Column A contains dates, Column B contains the salesperson's name, and Column C contains the sale amount. Having consistent headers is critical because the script will rely on column indices to identify which data to report.
- Open the Apps Script Editor: In your Google Sheet, go to the top menu and select Extensions > Apps Script. This opens a new browser tab with the script editor. Note that menu labels may differ slightly depending on your Google Workspace version or region.
- Name Your Project: Click on "Untitled project" at the top left of the editor and rename it to something descriptive, such as "Weekly Sales Reporter," to make it easier to manage if you have multiple scripts across different sheets.
- Write the Data Extraction Logic: Delete any existing placeholder code in the
Code.gsfile. Start by defining the spreadsheet and the specific sheet you want to pull data from. UseSpreadsheetApp.getActiveSpreadsheet()to target the current file andgetSheetByName("SalesData")to target your specific tab. This ensures the script doesn't accidentally pull data from the wrong sheet if you add more tabs later. - Define the Reporting Range: Use
getDataRange().getValues()to pull all the data from the sheet into a two-dimensional array. This is more efficient than pulling cells one by one. For example,var data = sheet.getDataRange().getValues();creates a variable that holds every row and column of your dataset. - Implement Filtering and Calculation: Create a loop to iterate through the data array. Since the first row usually contains headers, start your loop at index 1 (
for (var i = 1; i < data.length; i++)). Inside the loop, add logic to sum the values in the third column (index 2) or filter for a specific salesperson. For a total report, create a variablevar total = 0;and add the value ofdata[i][2]to it during each iteration of the loop. - Format the Report Message: Once the calculations are complete, construct a string that will serve as your report. Use template literals or concatenation to make the report readable. For example:
var message = "The total sales for this period are: " + total;. You can expand this to include a breakdown of sales per person by using a JavaScript object to track totals for each unique name found in Column B. - Set Up the Delivery Method: To send the report via email, use the
MailApp.sendEmail()method. This requires two main arguments: the recipient's email address and the subject line, followed by the body of the email (yourmessagevariable). Example:MailApp.sendEmail("manager@example.com", "Weekly Sales Report", message);. - Test the Script: In the Apps Script editor, select your function from the dropdown menu at the top and click the "Run" button. Google will prompt you for permissions. You must click "Review Permissions," select your account, click "Advanced," and then "Go to [Project Name] (unsafe)" to authorize the script to access your sheets and send emails on your behalf.
- Automate the Report with Triggers: To avoid running the script manually, click the clock icon (Triggers) on the left-hand sidebar of the Apps Script editor. Click "+ Add Trigger," select the function you just wrote, and change the event source to "Time-driven." You can then choose a specific frequency, such as "Weekly timer" or "Daily timer," to ensure the report is sent automatically without manual intervention.
Common Mistakes
One of the most frequent errors is forgetting that JavaScript arrays are zero-indexed. If your data is in Column C, you must reference it as index 2, not index 3. Referencing index 3 in a three-column sheet will result in an "undefined" error or a crash, as the script is looking for a fourth column that doesn't exist.
Another common mistake is failing to handle empty cells. If a cell in your "Amount" column is blank, the script may attempt to add a null value to a number, which can result in NaN (Not a Number) appearing in your final report. Always include a check, such as if (!isNaN(data[i][2])), to ensure you are only summing actual numbers.
Many users also forget to update the sheet name in the script. If you rename your tab from "SalesData" to "Sales 2024," the script will fail because getSheetByName("SalesData") will return null. Always ensure the string in your code matches the tab name exactly, including capitalization and spaces.
Tips
To make your reports more professional, use HTML emails instead of plain text. Instead of MailApp.sendEmail(), you can use GmailApp.sendEmail() and pass an options object containing htmlBody. This allows you to use <br> for line breaks and <b> for bold text, making the report much easier for stakeholders to scan.
If you are dealing with thousands of rows, avoid using getValue() inside a loop. Calling the spreadsheet service repeatedly is slow and can cause the script to time out. Always use getValues() once to pull the entire range into an array, process the data in memory, and then write the results back to the sheet or send the email in one go.
Consider adding a "Last Reported" timestamp to your sheet. After the script successfully sends the report, have it write the current date and time into a specific cell. This provides a visual confirmation that the automation is working and helps you track when the last data sync occurred.
Troubleshooting
If the script does not run, first check the "Execution log" at the bottom of the Apps Script editor. This log will tell you exactly which line caused the error. If you see a "Permission Denied" error, it usually means the script's authorization has expired or was revoked; try running the script manually once to trigger the permission pop-up again.
If the email is not arriving, check your "Sent" folder in Gmail. If the email is there but the recipient hasn't received it, the issue is likely with the recipient's spam filter rather than the script. If the email is not in the Sent folder, check for errors in the MailApp line of your code, specifically ensuring the email address is enclosed in quotes and is formatted correctly.
When the report shows incorrect totals, verify the data types in your sheet. Sometimes numbers are formatted as text, which causes JavaScript to concatenate them (e.g., "10" + "20" becomes "1020" instead of 30). Use the Number() function in your script, such as Number(data[i][2]), to force the value into a numeric format before adding it to your total.
Frequently Asked Questions
Can I send the report to multiple people?
Yes. In the sendEmail function, you can provide a comma-separated string of email addresses (e.g., "boss@example.com, assistant@example.com") as the recipient argument.
Is there a limit to how many emails the script can send?
Yes, Google imposes daily quotas on the number of emails sent via Apps Script. These limits vary depending on whether you have a personal @gmail.com account or a paid Google Workspace account.
Can the script report only data from the last 7 days?
Yes. You can create a new Date() object in JavaScript, subtract 7 days from it, and then use an if statement inside your loop to compare the date in Column A with your calculated cutoff date.
Can I attach a PDF of the sheet to the email?
While more complex, you can use the getAs('application/pdf') method on the spreadsheet object to convert the sheet into a PDF blob and then include that blob in the attachments array of the sendEmail options.
Do I need to keep the spreadsheet open for the trigger to work?
No. Time-driven triggers run on Google's servers in the cloud. Once the trigger is set, the script will execute at the scheduled time regardless of whether your browser is open or your computer is turned on.