首页 > 解决方案 > 获取 Google 表格值时保持“表格状态”

问题描述

我有一份每周需要向其发送时间表的人员列表。日程安排和需要联系的人的电子邮件列表都在 Google 表格上。我想创建一个脚本,(a)获取时间表,(b)将其发送到电子邮件列表。

我现在的问题是我的 Google Apps 脚本代码仅将时间表作为字符串发送(例如“role1、person1、role2、person2、role3、person3”),而不是将其格式“保持”为表格,

我考虑过一个循环,它会获取每一行的值并在末尾添加一个“\n”值,这会在每个人之后破坏字符串。这不是一个不可行的解决方案,但我更愿意保留表格,因为它更具可读性。

我怀疑我需要在 Google Apps 脚本中创建一个 HTML 表格,用我的电子表格中的值填充它,然后将该 HTML 表格设置为我的电子邮件正文。这看起来很奇怪,因为它已经是一个表格(在电子表格中)。

有没有办法在保持“表状态”的同时获取值?如果不是,那么创建/填充 HTML 表格的基本原理是什么?

到目前为止,这是我的代码,供参考:

function WeeklyReminder() {
  var ss = SpreadsheetApp.getActiveSpreadsheet(); // this directs the script to the spreadsheet
  var sheet = ss.getSheetByName("Automated WVS Weekly Reminder Email"); // this directs the script to the right sheet

  var schedule_values = sheet.getRange("D2:E").getDisplayValues(); // this gets the schedule values; "display values" because we want "what's seen," and not the function that's used to populate the cell

  Logger.log("schedule_values = " + schedule_values);

  var test_email = "o...@...org";
  var volunteer_values = sheet.getRange("B2:B").getDisplayValues();

  Logger.log("volunteer_values = " + volunteer_values);

  MailApp.sendEmail({
     to: test_email,
     subject: 'WVS Weekly Reminder',
     htmlBody: schedule_values.toString(),
     });
}

注意:我知道我的 htmlBody 目前发送...toString(),这就是我想要改变的。

标签: google-apps-scriptgoogle-sheets

解决方案


构建html表

function WeeklyReminder() {
  var ss=SpreadsheetApp.getActive();
  var sheet=ss.getSheetByName("Automated WVS Weekly Reminder Email");
  var vs=sheet.getRange(1,4,sheet.getLastRow(),2).getDisplayValues();
  var html='<style>td,th{border:1px solid black;}</style><table>';
  vs.forEach(function(r,i){
    if(i==0) {
      html+=Utilities.formatString('<tr><th>%s</th><th>%s</th></tr>',r[0],r[1]);//I changed the range so that it included the headers
    }else{
      html+=Utilities.formatString('<tr><td>%s</td><td>%s</td></tr>',r[0],r[1]);
    }
    html+='</table>';
  });
  var test_email="o...@...org";
  var volunteer_values=sheet.getRange(2,2,sheet.getLastRow()-1,1).getDisplayValues();
  MailApp.sendEmail({to: test_email,subject: 'WVS Weekly Reminder',htmlBody:html});
}

推荐阅读