首页 > 解决方案 > Webhook 到 Google 表格 - 想要替换而不是附加行

问题描述

我对 App Script 相当陌生,但我搜索了类似的问题,但没有看到明确的答案。我希望有人可以在这里帮助我。

我为公园/休闲空间开发物联网解决方案并使用 Particle 平台。我按照这个 Particle App note 让我的每台设备每天早上都发送它们的配置快照,这样即使设备处于睡眠状态/断开连接,我也可以轻松查看车队的状态。

https://docs.particle.io/datasheets/app-notes/an011-publish-to-google-sheets/

我修改了这个例子,它运行良好,除了一件事:如果它是一个新设备,我想在工作表上附加一个新行,但如果设备之前连接过,我想替换现有行。这样,表格反映了车队的当前状态,并且长度不会持续增长(就像现在一样)。

这是我当前脚本中的相关代码:

function doPost(e) {
  // e.parameter.event
  // e.parameter.data
  // e.parameter.coreid
  // e.parameter.published_at "2016-04-16T13:37:08.728Z"

  var particleApiToken = '{{API Token Here}}';

  var publishedAt = new Date(e.parameter.published_at);
  var cacheKey = 'deviceName';

  var dataArray = [];
  try {
    dataArray = JSON.parse(e.parameter.data);
  }
  catch(e) {
  }
  
  var cache = CacheService.getScriptCache();
  var deviceNameCache = cache.get(cacheKey);
  
  if (!deviceNameCache) {
    // The device name was not cached, so use the Particle Cloud API
    var result = UrlFetchApp.fetch('https://api.particle.io/v1/devices?access_token=' + particleApiToken);   
    var resultJson = JSON.parse(result.getContentText());
    
    deviceNameCache = {};

    for(var ii = 0; ii < resultJson.length; ii++) {
      deviceNameCache[resultJson[ii].id] = resultJson[ii].name;
    }
    cache.put(cacheKey, JSON.stringify(deviceNameCache));
  }
  else {
    deviceNameCache = JSON.parse(deviceNameCache);
  }
  
  // Use the device name if known, otherwise use Device ID
  var deviceName = deviceNameCache[e.parameter.coreid];
  if (!deviceName) {
    Logger.log('Unknown device ID');
    return;
  }

  var sheet = SpreadsheetApp.getActiveSheet();

  var row = [e.parameter.coreid, deviceName, publishedAt];

  row = row.concat(dataArray);

  sheet.appendRow(row);

  var result = {};
  result.ok = true;

  return ContentService.createTextOutput(JSON.stringify(result))
    .setMimeType(ContentService.MimeType.JSON);
}

任何建议将不胜感激。

谢谢,芯片

标签: google-apps-script

解决方案


感谢用户@idfurw 的建议,我能够修改代码以覆盖现有条目或替换它们(如果存在)。我原始帖子中的 appendRow 行已替换为以下代码:

  // This is the new section that determines if a row should be appended or overwritten
  // Row numbers are printed in the last column for testing and will be removed
  var documentProperties = PropertiesService.getDocumentProperties();           // Store properties in the document
  var rowIndex = documentProperties.getProperty(e.parameter.coreid);            // Index will tbe the deviceID

  if (!rowIndex) {                            // Row information not found - new row needed
    rowIndex = sheet.getLastRow() + 1;        // Get the last row number
    documentProperties.setProperty(e.parameter.coreid, rowIndex);    // Store the row number in the properties for next time
    row = row.concat(rowIndex);               // Concatenate the row number - for testing - to be removed
    sheet.appendRow(row);                     // Add this row to the end of the sheet
    Logger.log('New Entry - Appended');
  }
  else {
    row = row.concat(rowIndex);               // Concatenate the row number - for testing - to be removed
    sheet.getRange(Math.floor(rowIndex), 1, 1, row.length).setValues([row]);    // Overwrite the row
    Logger.log('Existing Entry - Overwritten');
  }

再次感谢您的帮助,我希望其他人可以从这种方法中受益 - 或提出更好的方法!

芯片


推荐阅读