从Google电子表格发送电子邮件,省略逗号

时间:2013-08-22 14:01:37

标签: google-apps-script google-sheets

所有

我使用下面的类似脚本从Google电子表格发送电子邮件:

// Sends an email when .......
function emailInfoRequired(row) { 
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var subject = "Info Needed: " + sheet.getRange("F19").getValues();
  var recipients = "email@email.com"
  var message = "<HTML><BODY>" 
    + "<P>" + sheet.getRange("K1").getValues()
    + "<BR>" + sheet.getRange("K2").getValues()
    + "</HTML></BODY>"; 
  MailApp.sendEmail(recipients, subject, "", {htmlBody: message});
}

我想做的不是使用单个单元格,而是想包含一个范围,例如:sheet.getRange(“K2:N2”)。getValues()

问题是,当我这样做时,电子邮件正文在该范围内的每个单元格之间都有一个逗号,使得电子邮件没有任何意义加上看起来很难看。我尝试将单元格格式化为纯文本,但没有帮助。有没有办法发送范围的电子邮件而不显示逗号?

2 个答案:

答案 0 :(得分:1)

Range.getValues()返回一个2D数组,并在您的电子邮件中打印此2D数组的字符串表示形式。根据您希望在电子邮件中显示的方式,您必须单独处理每个元素。有点像...

function emailInfoRequired(row) { 
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var subject = "Info Needed: " + sheet.getRange("F19").getValues();
  var recipients = "email@email.com"
  var values = sheet.getRange("K2:N2").getValues();
  var message = "<HTML><BODY>" ;
  for (var row = 0 ; row < values.length ; row++){
    message +=  "<P>" ;
    for (var col= 0 ; col < values[row].length ; col++){
      message +=  "<BR>" + values[row][col];
    }
  }
  message  += "</HTML></BODY>"; 
  MailApp.sendEmail(recipients, subject, "", {htmlBody: message});
}

答案 1 :(得分:1)

你甚至可以通过使用这样的html表来使它更优雅:

// Sends an email when .......
function emailInfoRequired(row) { 
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var subject = "Info Needed: " + sheet.getRange("F19").getValues();
  var recipients = "testmail@gmail.com"
  var data = sheet.getRange('A2:C25').getValues();// define your range here
  var message = '<HTML><BODY><table style="background-color:lightblue;border-collapse:collapse;" border = 1 cellpadding = 5><tr>';// change eventually the color here
  for (var row=0;row<data.length;++row){
    for(var col = 0;col<data[0].length;++col){
      message += '<td>'+data[row][col]+'</td>';
    }
    message += '</tr><tr>';
  }
    message += '</tr></table></body></HTML>';
   MailApp.sendEmail(recipients, subject, "", {htmlBody: message});
}

插图示例:

enter image description here