π’ Introduction
Are you tired of manually generating monthly reports for your team or clients? Imagine clicking one button to automatically:
- Add Data to a Google Sheet
- Create a Google Doc Report with the live sheet data
- Embed a Dynamic Chart in the document
- Export the Document as a PDF
- Email the PDF to your inbox β all done automatically!
With Google Apps Script, you can achieve all this with a few lines of code. In this guide, weβll walk you through how to set up this automation step-by-step.
π What Will This Script Do?
This Google Apps Script does the following:
- Add Sample Sales Data to a Google Sheet.
- Create a New Google Doc for the report.
- Insert a Data Table directly from the sheet into the Google Doc.
- Generate a Dynamic Chart from the sheetβs data.
- Embed the Chart as an Image in the Google Doc.
- Export the Google Doc as a PDF.
- Send the PDF Report via Email to the person who runs the script.
π Full Apps Script Code
Here is the complete script you need to get started. Follow the instructions below to add it to your Google Sheet.
function onOpen() {
const ui = SpreadsheetApp.getUi();
ui.createMenu('π Custom Report')
.addItem('π Create Report as New Doc & Email PDF', 'createDocAndEmailPDF')
.addToUi();
}
function AddData() {
const spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
const sheet = spreadsheet.getActiveSheet();
sheet.clear(); // Clear existing content
const sampleData = [
['Month', 'Sales'],
['January', 1200],
['February', 1500],
['March', 1000],
['April', 1800],
['May', 2000],
['June', 1700],
['July', 2500],
['August', 2300],
['September', 1900],
['October', 2200],
['November', 2100],
['December', 2400]
];
sheet.getRange(1, 1, sampleData.length, sampleData[0].length).setValues(sampleData);
}
function createDocAndEmailPDF() {
const spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
const sheet = spreadsheet.getActiveSheet();
const dataRange = sheet.getDataRange();
const data = dataRange.getValues(); // Extract live data from the sheet
const doc = DocumentApp.create('Monthly Sales Report');
const docId = doc.getId();
const body = doc.getBody();
body.appendParagraph('π Monthly Sales Report').setHeading(DocumentApp.ParagraphHeading.HEADING1);
body.appendParagraph('This document provides an overview of the monthly sales for the current year. Below you will find the detailed sales data along with a visual representation in the form of a chart.');
body.appendParagraph('π Sales Data Table');
body.appendTable(data); // Insert the live data directly from the spreadsheet
// Step 5: Check if a chart exists, if not, create one
let chartBlob;
const charts = sheet.getCharts();
if (charts.length > 0) {
// Reuse the existing chart
Logger.log('Chart already exists, reusing it.');
chartBlob = charts[0].getAs('image/png');
} else {
// Create a new chart
Logger.log('No chart found, creating a new one.');
const chart = sheet.newChart()
.setChartType(Charts.ChartType.COLUMN)
.addRange(dataRange)
.setPosition(5, 3, 0, 0)
.setOption('title', 'Monthly Sales Report')
.build();
sheet.insertChart(chart);
// Wait for the chart to render properly
Utilities.sleep(2000);
// Get the newly created chart
const updatedCharts = sheet.getCharts();
chartBlob = updatedCharts[0].getAs('image/png');
}
// Insert the chart image into the document
body.appendParagraph('π Sales Chart');
body.appendImage(chartBlob);
// Save and close the document
doc.saveAndClose();
const pdfBlob = exportDocumentAsPDF(docId);
const emailAddress = Session.getActiveUser().getEmail();
const subject = 'Monthly Sales Report';
const bodyMessage = 'Attached is your automatically generated Monthly Sales Report PDF.';
MailApp.sendEmail({
to: emailAddress,
subject: subject,
body: bodyMessage,
attachments: [pdfBlob]
});
Logger.log('Email sent to ' + emailAddress);
}
function exportDocumentAsPDF(docId) {
const url = `https://docs.google.com/document/d/${docId}/export?format=pdf`;
const token = ScriptApp.getOAuthToken();
const response = UrlFetchApp.fetch(url, {
headers: {
'Authorization': `Bearer ${token}`
}
});
const pdfBlob = response.getBlob().setName('Monthly_Sales_Report.pdf');
return pdfBlob;
}
π Step-by-Step Instructions
1οΈβ£ Add the Script
- Open Google Sheets.
- Click Extensions β Apps Script.
- Paste the code above into the script editor.
- Click Save (πΎ) or press Ctrl + S.
2οΈβ£ Run the Script
- Run the
onOpen()
function to create the custom menu. - Go back to your Google Sheet and refresh the page.
3οΈβ£ Use the Custom Menu
- Click π Custom Report in the Google Sheet menu.
- Click π Create Report as New Doc & Email PDF.
- The script will automatically generate and email the PDF report.
π Sample Data Table
Month | Sales |
---|---|
January | 1200 |
February | 1500 |
March | 1000 |
April | 1800 |
May | 2000 |
June | 1700 |
July | 2500 |
August | 2300 |
September | 1900 |
October | 2200 |
November | 2100 |
December | 2400 |
π Expected PDF Report
The PDF will have the following content:
- Title: π Monthly Sales Report
- Introduction: Overview of the reportβs purpose.
- Table: A live table with real-time data from the Google Sheet.
- Chart: A chart based on the live data from the sheet.
π Customization Options
1οΈβ£ Change Report Title
Change the title from Monthly Sales Report to something custom:
const doc = DocumentApp.create('Weekly Sales Report');
2οΈβ£ Customize Email
Change the email to be sent to someone else:
const emailAddress = 'manager@example.com';
3οΈβ£ Change Chart Type
Change the chart type from Charts.ChartType.COLUMN to LINE, PIE, BAR etc.:
.setChartType(Charts.ChartType.LINE)
π Key Features Recap
- Dynamic Data: Uses live data from Google Sheets.
- Automatic Charting: Inserts a chart based on the data.
- Google Doc Export: Data and charts are embedded in a professional document.
- Email PDF: Exports the document as a PDF and emails it.
π Use Cases
- Sales Reports: Automatically generate sales reports for clients or managers.
- Employee Reports: Email employee performance reports.
- Project Reports: Automatically generate a project status PDF.
- Data-Driven Marketing: Send performance reports to clients.
π Final Thoughts
This Google Apps Script provides a powerful, fully automated reporting system. It pulls live data, builds charts, and generates a professional document thatβs emailed as a PDF. Itβs perfect for generating weekly, monthly, or ad-hoc reports for managers, clients, or teams.
