将Google表格邮寄为CSV

时间:2017-04-04 19:57:12

标签: csv google-sheets gmail-api google-sheets-api

只是尝试获取当前的电子表格标签并将其作为* .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]});
}

2 个答案:

答案 0 :(得分:0)

好了一堆乱糟糟的东西,我终于偶然发现了一个简单易用的解决方案。 (告诉你即使是盲猪也能找到玉米穗)。请注意,它不发送文件,而是实际发送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);
}

答案 1 :(得分:0)

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

完全归功于: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"}]});
}
相关问题