Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Use Office Scripts to save a worksheet as a PDF and email it to yourself or your team.
Note
The script in this sample is provided as a preview for developers and may change based on feedback that we receive. Do not use this script in a production environment.
Solution
- Create a new Excel file in your OneDrive.
- Add data to your workbook.
- Create the script from this sample.
- Replace
name@email.com
in this sample with your desired recipient email address. - Adjust the
subject
andcontent
values. - Run the script.
Sample code: Save as a PDF and send via email
/**
* This script saves a worksheet as a PDF, downloads that PDF to your computer, and emails the PDF to a recipient.
*/
function main(workbook: ExcelScript.Workbook) {
// Create the PDF.
const pdfObject = OfficeScript.convertToPdf();
const pdfFile = { name: "report.pdf", content: pdfObject }; // Enter your desired PDF name here.
// Download the PDF.
OfficeScript.downloadFile(pdfFile); // Not required. Remove this line if you don't want to download the PDF.
// Email the PDF.
OfficeScript.sendMail({
to: "name@email.com", // Enter your recipient email address here.
subject: "[Demo] Monthly Sales Report", // This is the subject of your email.
content: "Here's the Monthly Sales Report", // This is the content within your email.
attachments: [pdfFile]
})
}
Tip
Use the properties of the MailProperties interface to add more details to your email, such as cc
, bcc
, and importance
values.
Troubleshooting
Error: Protected document
The sensitivity label for your workbook is preventing the script from sending an email. To resolve this error, change the sensitivity label of your workbook to General, Public, or Non-Business. Reload the workbook, and then run the script again.
Office Scripts