使用自动更新将IMPORTXML导入到Google Apps脚本中

时间:2017-08-26 00:17:33

标签: google-apps-script

我正在尝试使用Google工作表应用脚本来使用我正在使用的IMPORTXML。

A1
=importxml("http://www.nfl.com/liveupdate/scorestrip/ss.xml","//@q")

A2
=importxml("http://www.nfl.com/liveupdate/scorestrip/ss.xml","//@h")

数据来自A1:B16

根据我在网上发现的脚本让它自动刷新:

function getData() {
  var queryString = Math.random();

  var cellFunction1 = '=IMPORTXML("' + SpreadsheetApp.getActiveSheet().getRange('A1').getValue() + '?' + queryString + '","'+ SpreadsheetApp.getActiveSheet().getRange('A2').getValue() + '")';
  SpreadsheetApp.getActiveSheet().getRange('C1').setValue(cellFunction1);

  var cellFunction2 = '=IMPORTXML("' + SpreadsheetApp.getActiveSheet().getRange('A4').getValue() + '?' + queryString + '","'+ SpreadsheetApp.getActiveSheet().getRange('A5').getValue() + '")';
  SpreadsheetApp.getActiveSheet().getRange('C2').setValue(cellFunction2);
}

我不知道我应该在该代码中添加/替换我的内容。如果有人可以帮我解释一下我应该改变什么来让它在我的工作表中工作/提供一些可能看起来会有很大帮助的例子。

我很欣赏

3 个答案:

答案 0 :(得分:0)

您可以在getFormula()功能中使用setFormula()然后time-driven trigger来更新该功能。以下是相关SO post的代码段:

/**
 * Go through all sheets in a spreadsheet, identify and remove all spreadsheet
 * import functions, then replace them a while later. This causes a "refresh"
 * of the "import" functions. For periodic refresh of these formulas, set this
 * function up as a time-based trigger.
 *
 * Caution: Formula changes made to the spreadsheet by other scripts or users
 * during the refresh period COULD BE OVERWRITTEN.
 *
 * From: https://stackoverflow.com/a/33875957/1677912
 */
function RefreshImports() {
  var lock = LockService.getScriptLock();
  if (!lock.tryLock(5000)) return;             // Wait up to 5s for previous refresh to end.
  // At this point, we are holding the lock.

  var id = "YOUR-SHEET-ID";
  var ss = SpreadsheetApp.openById(id);
  var sheets = ss.getSheets();

  for (var sheetNum=0; sheetNum<sheets.length; sheetNum++) {
    var sheet = sheets[sheetNum];
    var dataRange = sheet.getDataRange();
    var formulas = dataRange.getFormulas();
    var tempFormulas = [];
    for (var row=0; row<formulas.length; row++) {
      for (col=0; col<formulas[0].length; col++) {
        // Blank all formulas containing any "import" function
        // See https://regex101.com/r/bE7fJ6/2
        var re = /.*[^a-z0-9]import(?:xml|data|feed|html|range)\(.*/gi;
        if (formulas[row][col].search(re) !== -1 ) {
          tempFormulas.push({row:row+1,
                             col:col+1,
                             formula:formulas[row][col]});
          sheet.getRange(row+1, col+1).setFormula("");
        }
      }
    }

    // After a pause, replace the import functions
    Utilities.sleep(5000);
    for (var i=0; i<tempFormulas.length; i++) {
      var cell = tempFormulas[i];
      sheet.getRange( cell.row, cell.col ).setFormula(cell.formula)
    }

    // Done refresh; release the lock.
    lock.releaseLock();
  }
}

希望这有帮助。

答案 1 :(得分:0)

我一直在做一些相关的工作,最后使用this StackOverFlow Post中的代码解决了这个问题,但是我需要添加一些额外的位。

这对我来说效果不佳,因此我进行了一些更改并添加了额外的日志记录,以使其对我来说可以理解。这是去:

function RefreshImports() {
  var lock = LockService.getScriptLock();
  if (!lock.tryLock(5000)) return;             // Wait up to 5s for previous refresh to end.
  
  var now = new Date();
  // Show start time on log
  Logger.log("Starting Running at " + now.toLocaleTimeString());
  
  var url = "URL OF YOUR SHEET";
  var sheetName = "NAME OF YOUR SHEET";
  
  var ss = SpreadsheetApp.openByUrl(url);
  var sheet = ss.getSheetByName(sheetName);

    var dataRange = sheet.getDataRange();
    var formulas = dataRange.getFormulas();
    var tempFormulas = [];
    for (var row=0; row<formulas.length; row++) {
      for (var col=0; col<formulas[0].length; col++) {
        // Blank all formulas containing any "import" function
        // See https://regex101.com/r/bE7fJ6/2
        var re = /.*[^a-z0-9]import(?:xml|data|feed|html|range)\(.*/gi;
        if (formulas[row][col].search(re) !== -1 ) {
          tempFormulas.push({row:row+1,
                             col:col+1,
                             formula:formulas[row][col]});
          sheet.getRange(row+1, col+1).setFormula(""); //cleans up the formula
        }
        
      }
    }
    // After a pause, replace the import functions
        Utilities.sleep(500);
        for (var i=0; i<tempFormulas.length; i++) {
          var cell = tempFormulas[i];
          sheet.getRange( cell.row, cell.col ).setFormula(cell.formula);
          var nowLogger = new Date();     
          Logger.log("Update import from row " + cell.row + " col " + cell.col + " done at " + nowLogger.toLocaleTimeString());
          Utilities.sleep(1000); //adding to try to control the amount of parallel connections from the Sheet
        }
      
  
    // Show Finished time on log
  var now = new Date();
  Logger.log("Sources from URLs were last updated at " + now.toLocaleTimeString());

    // Done refresh; release the lock.
  lock.releaseLock();
  
}

然后,我在https://script.google.com/home/triggers的项目中添加了基于时间的触发器,该触发器可处理自动更新的执行。

我希望这会有所帮助!

答案 2 :(得分:0)

它实际上不起作用。我的意思是它确实不会刷新单元格,而使用它可以工作的随机数:

function getData() {
  var queryString = Math.random();

  var Xpath_1 = "/html/body/text()";
  var importXpath_1 = '=IMPORTXML("' + 'http://www.pde-racing.com/trams/tram.php?id=999&valor=1&manega=Entrenament+1&dbTemps=Event999Ex.scdb&dbInscrits=Event999.scdb&name=&_=1616318271525' + '?' + queryString + '";"'+ Xpath_1 + '")';
  
  SpreadsheetApp.getActiveSheet().getRange('B39').setValue(importXpath_1);
}