首页 > 解决方案 > GoogleSheets股票价格电子邮件警报的实施

问题描述

我有一个 Googlesheets 股票价格警报脚本正在为 GoogleSheet 中的一只股票运行。它会根据目标价格检查当前价格,并在价格较低时发送电子邮件提醒。如何扩展我的脚本以检查电子表格中的股票列表?我想我需要一个循环或其他东西来向下滚动每一行,但我不确定如何做到这一点。我的单行检查工作代码:

 // Fetch the stock price
   var stockNameRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1").getRange("A2");  
   var currentPriceRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1").getRange("C2"); 
   var targetPriceRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1").getRange("B2");
   var stockName = stockNameRange.getValue();
   var currentPrice = currentPriceRange.getValue();
   var targetPrice = targetPriceRange.getValue();   

 // Check stock prices
   if (currentPrice < targetPrice){

// Fetch the email address
   var emailRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet2").getRange("B2");
   var emailAddress = emailRange.getValues();

// Send Alert Email.
   var message = stockName +" "+ currentPrice +" is below your target price of "+ targetPrice;
   var subject = 'Low Price Alert';
   MailApp.sendEmail(emailAddress, subject, message);
   }
 }```

标签: google-apps-scriptgoogle-sheets

解决方案


尝试这个:

function sdk(){
  // Fetch the stock price
  var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("sheet1");
  var data = ss.getRange("A13:C23").getValues(); // gets all the data from the three cols and puts it into a 2D array.
  var emailRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet2").getRange("B2");
  var emailAddress = emailRange.getValues();
  var message = "";

  for (var i = 0; i < data.length; i++){ // will go over the rows that you stored in data with data[i][0] being the stock name, data[i][1] being the target and data[i][2] being the current value.
    // Check stock prices
    if (data[i][2] < data[i][1]){
      // Send Alert Email.
      message += data[i][0] +" "+ data[i][2] +" is below your target price of "+ data[i][1] + " \n";
    }
  }
   if (message != "")
      MailApp.sendEmail(emailAddress, 'Low Price Alert', message);
}

请记住,我使用范围A13:C23是因为我有我的测试数据,您必须使用您的范围,具体取决于您如何构建工作表,但是此代码将循环并将您想要的信息发送到电子邮件中。它基本上保持将“警报”行附加到消息中,并在循环结束时将所有内容一起发送。

使用 Apps 脚本时,尝试限制对 API 的调用以使代码更加优化,这就是为什么我在获取工作表时更改了将范围存储为单个调用的方式var ss = ...,这也是使用getValues()很重要的原因,这只是对 API 的一次调用,而不是获取单个单元格的值。


推荐阅读