【问题标题】:Getting a Google Spreadsheet Cell's Image URL获取 Google 电子表格单元格的图像 URL
【发布时间】:2014-07-08 03:44:05
【问题描述】:

我有一个 Google 电子表格,每行的第 2 列和第 3 列都有一个图像,我正在尝试将所有电子表格数据记录到控制台(现在)。我无法访问每个单元格中的图像,因为 getValue() 函数不会返回图像的源 URL。所有图像都使用=image("http://imagesource.com",3) 插入到电子表格中。到目前为止,这是我从 Google 提供的默认 readRows 函数编辑的内容:

  function readRows() {
    var sheet = SpreadsheetApp.getActiveSheet();
    var rows = sheet.getDataRange();
    var numRows = rows.getNumRows();
    var numCols = rows.getNumColumns();

    for (var i = 2; i <= numRows - 1; i++) {
      for (var j = 1; j <= numCols; j++) {
        // columns 2 and 3 always contain images  
        if (j == 2 || j == 3) {
          // gets the google spreadsheet url, not the original source url
          // of the image contained in the cell like I want it to
          var imgUrl = rows.getCell(i, j).getDataSourceUrl(); 
          Logger.log("[img]" + imgUrl + "[/img]");
        } else {
          var cellData = rows.getCell(i, j).getValue();
          Logger.log(cellData);
        }
      }
    }
  }

编辑:看起来我可以使用getFormula() 返回一个类似于=image("http://imagesource.com",3) 的字符串,但这仍然给我留下了处理字符串以仅包含URL 的问题。我不确定这是否可行,因为字符串看起来像是谷歌脚本中的原始数据类型。

【问题讨论】:

    标签: image url google-apps-script google-sheets


    【解决方案1】:

    Range.getValue() 返回单元格的计算值,在本例中是图像,而不是 URL。如您所见,您可以使用getFormula() 来获取创建图像的公式。您可以使用正则表达式从公式字符串中提取图像 URL。

    function getImageUrl(formula) {
      var regex = /=image\("(.*)"/i;
      var matches = formula.match(regex);
      return matches ? matches[1] : null;
    }
    

    如果 URL 是从另一个单元格或公式计算的,这将不起作用,但它应该适用于您列出的简单情况。

    【讨论】:

    • 完美运行,谢谢!我之前没有使用过正则表达式,所以我将看看它们的用途,以便将来解决类似的问题。
    【解决方案2】:

    使用查找和替换 编辑 > 查找和替换

    并在“查找和替换”框中选中“也在公式中搜索”

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-13
      • 1970-01-01
      • 1970-01-01
      • 2017-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多