以 CSV 格式邮寄 Google Sheet

Mailing Google Sheet as CSV

只是尝试获取当前电子表格选项卡并将其作为 *.csv 文件邮寄到某个地址。我已经经历了大量的先前问题,但还没有找到答案。这是改编自成功发送的 PDF 文件。唯一的问题是我需要 CSV 而不是 PDF。

function mailCSV() {
// Get the currently active spreadsheet URL (link)
// Or use SpreadsheetApp.openByUrl("<<SPREADSHEET URL>>");
// Send the CSV of the spreadsheet to this email address
   var email_send_address = "email@emailsample.com"; 
   var email_subject ='subject'
// Get the currently active spreadsheet URL (link)
   var ss = SpreadsheetApp.getActiveSpreadsheet();
   var url = "http://spreadsheets.google.com/feeds/download/spreadsheets/Export?key="+ ss + "&exportFormat=csv"; 

//var csv = DriveApp.getFileById(ss.getId()).getAs('application/csv').getBytes();
//var attachCSV = {fileName: email_subject,content:url,mimeType:'application/csv'};

  var res = UrlFetchApp.fetch(url);
  var attachments = [{fileName:"dg_request.csv", content: res.getContent(),mimeType:"application/vnd.csv"}];

MailApp.sendEmail(email_send_address, email_subject, {attachments: attachments});

// MailApp.sendEmail(email_send_address, email_subject, {attachments:[attachCSV]});
}

好吧,经过一番折腾,我终于找到了一个简单易行的解决方案。 (告诉你即使是一只瞎了眼的猪也能找到一穗玉米)。请注意,它不发送文件,而是实际发送 csv 作为消息的正文......这对我来说很好。

function mailRequestCSV() {

// Send the PDF of the spreadsheet to this email address
  var email_send_address = "david.fickes@sunrunhome.com"; 
  var email_subject = "datagen request"

// Get the currently active spreadsheet ID
  var fileID = SpreadsheetApp.getActiveSpreadsheet();

// Build the URL 
  var url = 'https://docs.google.com/spreadsheet/ccc?key='+fileID+'&output=csv';
  var response = UrlFetchApp.fetch(url);

  MailApp.sendEmail(email_send_address, email_subject, response);
}

作为附件发送的更好的答案:

全部归功于:https://gist.github.com/nirajkadam/0b41a01b8e739800c964

function mailRequestCSV() {

// Send the PDF of the spreadsheet to this email address
var recipients = "someone@somewhere.com"; 
var ssID = SpreadsheetApp.getActiveSpreadsheet().getId();
var sheetName = SpreadsheetApp.getActiveSpreadsheet().getName();
var email = Session.getActiveUser().getEmail();
var subject = "DataGenerationRequest ";
var body = "****NOTE: THIS IS AN AUTO COMPUTER-GENERATED REPORT****";
var requestData = {"method": "GET", "headers":{"Authorization":"Bearer "+ScriptApp.getOAuthToken()}};
var url = "https://docs.google.com/spreadsheets/d/"+ssID+"/export?format=csvx&id="+ssID;
var result = UrlFetchApp.fetch(url, requestData);
var contents = result.getContent();

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

2022 年 1 月尝试过,但对我不起作用。

我的解决方案是简单地将 URL 格式 更改为:

var url = 'https://docs.google.com/spreadsheets/d/' + SpreadSheetId + "/export?format=csv&gid=" + SheetId;

在哪里

SpeadSheetId = SpreadsheetApp.getActiveSpreadsheet().getId();
SheetId = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Name of your sheet").getSheetId();