谷歌工作表脚本将数据插入工作表

时间:2017-01-26 11:20:47

标签: google-apps-script google-sheets

所以我有一个脚本从服务器获取一些数据 我希望我的脚本将数据发布到工作表名称“market items” 如果我使用=getMarketItemsTrigger(1)直接从工作表运行脚本,我就可以使用了 它将所有11,669个项目发布到我的工作表中。

问题在于每次重新加载工作表时都会刷新;我需要它每月只运行一次 我一直在尝试创建一个脚本,在给定的工作表中不需要引用,但直接发布到预先命名的工作表但我无法弄清楚如何将数据放入工作表中

这是我正在使用的脚本文件

var version = '9a'
function getMarketItemsTrigger(refresh)
{
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName("Market Items");
  
  Logger.log(sheet.getMaxColumns());
  Logger.log(sheet.getMaxRows());
  sheet.clear();
 
  
  if(sheet.getMaxColumns()>2){
    Logger.log('deleting colums');
  sheet.deleteColumns(2, sheet.getMaxColumns()-2);
    
  }
  if(sheet.getMaxRows()>2){
     Logger.log('deleting rows');
   sheet.deleteRows(2,sheet.getMaxRows()-1);
  }
  
    var marketItemsEndpoint = 'https://crest-tq.eveonline.com/market/types/';
  var marketItemsResponse = JSON.parse(fetchUrl(marketItemsEndpoint));

  var totalPages = marketItemsResponse['pageCount'];

  var itemList = [];
  var headers = ['Item Name', 'ID'];
  itemList.push(headers);

  
  for (var currentPage = 1; currentPage <= totalPages; currentPage++)
  {
    Logger.log('Processing page ' + currentPage);
    var marketItems = marketItemsResponse['items'];
    for (var itemReference in marketItems)
    {
      var item = marketItems[itemReference];
      itemList.push([item['type']['name'], item['id']]);
      
     
    }

    if (currentPage < totalPages)
    {
      var nextEndpoint = marketItemsResponse['next']['href'];
      marketItemsResponse = JSON.parse(fetchUrl(nextEndpoint));
    }
    
    
    
  }
 
  //sheet.insertRows(1,itemList.length+1);
 // var range = sheet.getRange(1, 1,itemList.length+1,3);
  
//  for(var i = 1;i<itemList.length;i++){
    
//   range.getCell(i, 1).setValue([itemList]);
//    range.getCell(1, i).setValue(itemList.);
  //  }
 // Logger.log("don");
//sheet.getRange(1, 1, 1, itemList.length).setValues(itemList);
  
//  sheet.getRange(itemList.length+1, 2).setValues(itemList);
 // sheet.getDataRange().setValues([itemList]);
//  sheet.appendRow(itemList);
//  sheet.getRange(12+totalPages, 1, itemList.length, 1).setValues(itemList);
  return itemList;
}
/**
 * Private helper method that wraps the UrlFetchApp in a semaphore
 * to prevent service overload.
 *
 * @param {url} url The URL to contact
 * @param {options} options The fetch options to utilize in the request
 */
function fetchUrl(url)
{
  if (gcsGetLock())
  {
    // Make the service call
    headers = {"User-Agent": "Google Crest Script version " + version + " (/u/nuadi @Reddit.com)"}
    params = {"headers": headers}
    httpResponse = UrlFetchApp.fetch(url, params);
  }
    
  return httpResponse;
}


/**
 * Custom implementation of a semaphore after LockService failed to support GCS properly.
 * Hopefully this works a bit longer...
 *
 * This function searches through N semaphores, until it finds one that is not defined.
 * Once it finds one, that n-th semaphore is set to TRUE and the function returns.
 * If no semaphore is open, the function sleeps 0.1 seconds before trying again.
 */
function gcsGetLock()
{
  var NLocks = 150;
  var lock = false;
  while (!lock)
  {
    for (var nLock = 0; nLock < NLocks; nLock++)
    {
      if (CacheService.getDocumentCache().get('GCSLock' + nLock) == null)
      {
        CacheService.getDocumentCache().put('GCSLock' + nLock, true, 1)
        lock = true;
        break;
      }
    }
  }
  return lock;
}
/**
 * Private helper function that will check for a new version of GCS.
 */
function versionCheck()
{
  var versionEndpoint = 'https://raw.githubusercontent.com/nuadi/googlecrestscript/master/version';
  var newVersion = fetchUrl(versionEndpoint);

  if (newVersion != null)
  {
    newVersion = newVersion.getContentText().trim();
    Logger.log('Current version from Github: ' + newVersion);

    var message = 'You are using the latest version of GCS. Fly safe. o7';
    var title = 'No updates found';
    if (newVersion > version)
    {
      message = 'A new version of GCS is available on GitHub.';
      title = 'GCS version ' + newVersion + ' available!';
    }
    SpreadsheetApp.getActiveSpreadsheet().toast(message, title, 120);
  }
}

函数getMarketItemsTrigger中注释掉的所有代码都是我没有运气的情况。

此问题的简短版本是如何将itemList中的值发布到工作表市场项目中的a和b列

2 个答案:

答案 0 :(得分:0)

有两种方法可以做到这一点。如果您确实希望它作为自定义函数运行,则可以访问脚本属性服务。您可以在脚本属性中保存时间戳,并在每次自定义函数运行时进行检查。

  

https://developers.google.com/apps-script/reference/properties/

     

https://developers.google.com/apps-script/guides/sheets/functions#using_apps_script_services

第二种是创建一个时间触发器,每月将代码作为一个cron作业运行。

  

https://developers.google.com/apps-script/guides/triggers/installable#time-driven_triggers

     

https://developers.google.com/apps-script/guides/triggers/installable#managing_triggers_manually

答案 1 :(得分:0)

您可以通过添加:

将数组itemList写入工作表
//your code
ss.getSheetByName('name_of_sheet_here')
.getRange(1, 1, itemList.length, itemList[0].length)
.setValues(itemList) 
//more code (if needed)
} //end of code

- &GT;&GT;更改工作表名称和范围以适应。