强制刷新ImportXML

时间:2017-06-24 21:05:15

标签: google-sheets formulas

我想强制importXML每五分钟自动刷新一次。这是我试图运行的脚本并且收到错误&#34;错误的值(第7行,文件&#34; RefreshImports&#34;。我不知道为什么。我在这里找到它:Periodically refresh IMPORTXML() spreadsheet function < / p>

function RefreshImports() {
  var lock = LockService.getScriptLock();
  if (!lock.tryLock(5000)) return; // Wait up to 5s for previous 
  refresh to end.

  var id = "[YOUR SPREADSHEET ID]";
  var ss = SpreadsheetApp.openById(id);
  var sheet = ss.getSheetByName("[SHEET NAME]");
  var dataRange = sheet.getDataRange();
  var formulas = dataRange.getFormulas();
  var content = "";
  var now = new Date();
  var time = now.getTime();
  var re = /.*[^a-z0-9]import(?:xml|data|feed|html|range)\(.*/gi;
  var re2 = /((\?|&)(update=[0-9]*))/gi;
  var re3 = /(",)/gi;

  for (var row = 0; row < formulas.length; row++) {
    for (var col = 0; col < formulas[0].length; col++) {
      content = formulas[row][col];
      if (content != "") {
        var match = content.search(re);
        if (match !== -1) {
          // import function is used in this cell
          var updatedContent = content.toString().replace(re2, "$2update=" +
            time);
          if (updatedContent == content) {
            // No querystring exists yet in url
            updatedContent = content.toString().replace(re3, "?update=" + time +
              "$1");
          }
          // Update url in formula with querystring param
          sheet.getRange(row + 1, col + 1).setFormula(updatedContent);
        }
      }
    }
  }

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

  // Show last updated time on sheet somewhere
  sheet.getRange(7, 2).setValue("Rates were last updated at " +
    now.toLocaleTimeString())
}

在代码中显示&#34; [您的电子表格ID]&#34;,我要输入电子表格的名称是否正确?我对此一无所知。

这是my sheet

2 个答案:

答案 0 :(得分:0)

[YOUR SPREADSHEET ID]上,您应该添加电子表格ID,而不是它的名称。

的电子表格ID

https://docs.google.com/spreadsheets/d/1Xhgfr3z4EwPtjS4aahytU_3TOVxjNb8JvHo88h3nZaE/edit#gid=14522064

1Xhgfr3z4EwPtjS4aahytU_3TOVxjNb8JvHo88h3nZaE

答案 1 :(得分:0)

我发现使用URL代替id更容易,这是一些代码:

var url = "URL OF SPREADSHEET"; 
var sheetName = "NAME OF SPECIFIC SHEET";
var ss = SpreadsheetApp.openByUrl(url);
var sheet = ss.getSheetByName(sheetName);