通过电子邮件自动发送工作表的脚本

时间:2021-04-13 21:58:23

标签: google-apps-script google-sheets

我正在尝试通过脚本自动将工作簿的工作表(活动或非活动)和仅一张工作表而不是整个工作簿发送到电子邮件地址列表。此外,我希望将工作表附加到电子邮件时将其转换为 excel 格式。

感谢您的回答

2 个答案:

答案 0 :(得分:0)

试试这个:

function emailSpreadsheetAsPDF() {
  const sheetToPrint = 'SPREADSHEET_NAME'; // name of the sheet to print
  const ss = SpreadsheetApp.getSheetByName('SHEET_NAME'); // the sheets to use
  const email = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('SHEET_NAME').getRange('RANGE').getValue().toString(); // grab the email address from the specified cell 
  const subject = `SUBJECT - ${ss.getName()}`; // the subject of the email
  const body = "BODY"; // body of the email
  const shID = ss.getSheetByName(sheetToPrint).getSheetId(); // the ID of the sheet
  const url = 'https://docs.google.com/spreadsheets/d/SS_ID/export?'.replace('SS_ID', ss.getId()); // url of the spreadsheet
  const exportOptions =
    'exportFormat=pdf&format=xlsx' + // export as pdf / csv / xls / xlsx
    '&gid='+shID; // the sheet's Id
  var params = {method:"GET",headers:{"authorization":"Bearer "+ ScriptApp.getOAuthToken()}};
  
  // generate the file
  var response = UrlFetchApp.fetch(url+exportOptions, params).getBlob();
  
  // send the email to the specified address with the specified body text and attached file
    GmailApp.sendEmail(email, subject, body, {
      htmlBody: body,
      attachments: [{
            fileName: `EKOL Hungary - ${ss.getName()}` + ".xlsx",
            content: response.getBytes(),
            mimeType: "application/xlsx"
        }]
    });
}

只需将 SPREADSHEET_NAMESHEET_NAMERANGEBODY 替换为适用于您的电子表格的内容。

您可以在“触发器”菜单点(脚本编辑器的左侧)下添加一个触发器,以便在您希望脚本运行时自动运行该脚本。

答案 1 :(得分:0)

谢谢,但我没有使用它
但是通过结合几个脚本,我找到了一个有效的:

function onSubmit(e){
Logger.log('submit ran');
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();

//Send active sheet as email attachment

var ss = SpreadsheetApp.getActiveSpreadsheet()
var ssID = ss.getId();
var sheetgId = ss.getActiveSheet().getSheetId();
var sheetName = ss.getName();

var token = ScriptApp.getOAuthToken();

var email = "xxx@xx";
var subject = "xxxxx";
var body = "xxxxx";

var url = "https://docs.google.com/spreadsheets/d/"+ssID+"/export?" + "format=xlsx" + "&gid="+sheetgId+ "&portrait=false" + "&exportFormat=xlsx";

var result = UrlFetchApp.fetch(url, {
headers: {
'Authorization': 'Bearer ' + token
}
});

var contents = result.getContent();

MailApp.sendEmail(email,subject ,body, {attachments:[{fileName:sheetName+".xlsx", content:contents, mimeType:"application//xlsx"}]});
};

现在我想要的是能够将工作表发送到位于另一张工作表上的电子邮件地址。
同样在“主题”中,我想在活动表的单元格中组合“xxxx”+日期:“xxxx dd / mm / yyyy”

我还没想好怎么做!!!