Google Spreadsheet--使用ImportXML()将Google搜索结果导入单元格后,将单元格值,Google重定向网址转换为实际网址

时间:2014-07-18 19:32:40

标签: javascript google-sheets

示例单元格值为“https://www.google.com/url?q=http://en.wikipedia.org/wiki/Boricua_College&sa=U&ei=mTTIU4fhEs_jsASNy4G4Dg&ved=0CBQQFjAAOAE&usg=AFQjCNEnOjYOji3mdwT3_FS0L1_NCFk7GQ”(尽管在电子表格中所有网址都是纯文本格式),理想情况下我想用“http://en.wikipedia.org/wiki/Boricua_College”替换它。当我在脚本编辑器中运行程序时,电子表格会提示我输入一个列字母,因为它应该是,但之后什么都不做。它不会删除#N / A值,也不会修剪任何URL。

function trimLink() {
  var s = SpreadsheetApp.getActiveSheet();
  // set column to trim
  var c = Browser.inputBox("Please", "Type in the column name (e.g.: A, B, etc.)",   Browser.Buttons.OK_CANCEL);
  if (c != "cancel") {
   c = c.charCodeAt(0) - 64;
  }
  var r, v;
  // set length to cut from beginning of string
  var begLink = "https://www.google.com/url?q=";
  var begLen = begLink.length;
  var endLen;
  try
  {
    if(c != "cancel")
    {
      r = 2; // first row is row two
      while (r <= s.getLastRow()) {
        v = s.getRange(r, c).getValue();
        // #N/A is the result of failed importXML
        if (v != "" && v != "#N/A") {
          // initialize variable to hold value of string
          var link = String(v);
          for (var k = 0; k < link.length; k++) {
            // link must be trimmed at char & (&sa)
            if (link.charAt(k) == '&') {
              // set length to cut from end of string
              endLen = k;
              break;
            }
          }
          v = link.substr(begLen, endLen - 1);
        }
        else {
         v = "";
        }
        r++;
      }
    }
  } catch (e) {Browser.msgBox("Error Alert:", e.message, Browser.Buttons.OK);}
}

1 个答案:

答案 0 :(得分:0)

主要问题是我没有为细胞分配新值。最重要的是我使用substr而不是substring,但直到我的程序成功将单元格值更改为其他内容之后才意识到。

function trimLink() {
  var s = SpreadsheetApp.getActiveSheet();
  // input relevant column
  var c = Browser.inputBox("Please", "Type in the column name (e.g.: A, B, etc.)",   Browser.Buttons.OK_CANCEL);
  // represent letter input as column number
  if (c != "cancel") {
   c = c.charCodeAt(0) - 64;
  }
  var r, link;
  // length to cut from beginning of string
  var begLink = "https://www.google.com/url?q=";
  var begLen = begLink.length;
  var endLen = 0;
  try
  {
    if(c != "cancel")
    {
      r = 2; // first row is row two
      while (r <= s.getLastRow()) {
        link = String(s.getRange(r, c).getValue());
        // #N/A is the result of failed importXML
        if (link != "" && link != "#N/A") {
          while (link.charAt(endLen) != '&') {
            endLen++
          }
          s.getRange(r,c).setValue(link.substring(begLen, endLen));
        }
        else {
          // clear cell if importxml (outside of this program) had failed to extract a g search url
          s.getRange(r, c).setValue("");
        }
        r++;
      }
    }
  } catch (e) {Browser.msgBox("Error Alert:", e.message, Browser.Buttons.OK);}
}