保存工作表并将其通过电子邮件发送为 PDF

使用 Office 脚本将工作表另存为 PDF,并通过电子邮件将其发送给自己或团队。

解决方案

  1. 在 OneDrive 中创建新的 Excel 文件。
  2. 将数据添加到工作簿。
  3. 从此示例创建脚本。
  4. 将此示例中的 替换为 name@email.com 所需的收件人电子邮件地址。
  5. subject调整 和 content 值。
  6. 运行脚本。

示例代码:另存为 PDF 并通过电子邮件发送

/**
 * 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]
    })    
}

提示

使用 MailProperties 接口的属性向电子邮件添加更多详细信息,例如 ccbccimportance 值。

疑难解答

错误:受保护的文档

工作簿 的敏感度标签 阻止脚本发送电子邮件。 若要解决此错误,请将工作簿的敏感度标签更改为“常规”、“公共”或“非企业”。 重新加载工作簿,然后再次运行脚本。