google-apps-script - 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);
}
}```
解决方案
尝试这个:
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 的一次调用,而不是获取单个单元格的值。
推荐阅读
- c# - 如何将对象从客户端发送到服务器并反向?
- certificate - 证书上的“签名算法”到底是什么意思?使用哪种签名算法来签署我的证书?
- c++ - 不能用作函数,返回前的最后一行是错误
- android - 如何配置 Android Gradle 项目以过滤资源?
- javascript - 设置状态的新 Promise 接收箭头函数
- computer-vision - 如何使用 Viola Jones 算法将人脸检测为感兴趣区域并将其裁剪到矩形框?
- python - 加入列表最后几个元素并将新加入的项目附加回列表的最快和 Pythonic 方式
- python - python - 如何在python中拆分不包含分隔符的连接字符串?
- javascript - 如何正确过滤数组
- c# - Unity - 错误 CS106:类型“分数”不包含 scoreUp 的定义