从Google表格单元格插入来自URL的图像到Google文档

4

这段代码可以用来插入图片。

但我想从 Google 表格中获取图片的 URL。我在下面的代码中加入了 "UrlFetchApp.fetch("sourceSheet.getActiveCell().getValue()");" 来展示我的解决思路...

  function insertImage() {



  // Retrieve an image from the web.
  var resp = UrlFetchApp.fetch("sourceSheet.getActiveCell().getValue()");

  // Create a document.
  var doc = DocumentApp.openById("1qWnGAR_WBpHkSdY5frld0VNfHtQ6BSzGxlzVNDi5xMk");

  // Append the image to the first paragraph.
  doc.getChild(2).asParagraph().appendInlineImage(resp);
}

最终目标是在一列中放置文档的ID,另一列中放置要插入的图片的URL。我希望脚本能够运行,以便将每个图片插入到每个文档中。

2个回答

7
这里有一个可能的解决方案。当然,您需要用自己的文档ID替换文档和电子表格ID。
function insertImage() {
  // Get the target document.
  var doc = DocumentApp.openById("1DeAGfM1PXXXXXXXXXXXXXXXXXXwjjeUhhZTfpo");

  // Get the Spreadsheet where the url is defined
  var sheet = SpreadsheetApp.openById("0Agl8XXXXXXXXXXXXXXXXXXXXXXXXXRScWU2TlE");

  // Get the url from the correct celll
  var url = sheet.getRange("A1").getValue();

  // Retrieve an image from the web.
  var resp = UrlFetchApp.fetch(url);

  // Append the image to the first paragraph.
  doc.getChild(0).asParagraph().appendInlineImage(resp.getBlob());
}

3
这基于Eduardo的脚本(谢谢Eduardo)并添加了迭代遍历电子表格并在每行上执行此过程的功能。为了做到这一点,我使其能够在每行插入不同的文档中的不同图像。
由于AutoCrat目前不支持像这样插入图像,所以这是我找到的最佳解决方法。
要测试此脚本,我设置了lastRow = 3。将3更改为sheet.getLastRow()以对整个工作表进行操作。
另请注意,“getsheetbyname”使用单引号'XXX',因为其中有一个空格,否则会出错。
function insertImage() {
    var startRow = 2;  // First row of data to process
    var lastRow = 3;   // Last row of data to process

    for (var i = startRow; i <= lastRow; i++)
    {
        // Get the Spreadsheet where the url is defined
        var sheet = SpreadsheetApp.openById("0AsrSazSXVGZtdEtQOTFpTTFzWFBhaGpDT3FWcVlIasd").getSheetByName('88. Research');


        // Get the target document.
        var docid = sheet.getRange("F"+i).getValue();

        var doc = DocumentApp.openById(docid);

        // Get the url from the correct cell
        var url = sheet.getRange("D"+i).getValue();

        // Retrieve an image from the web.
        var resp = UrlFetchApp.fetch(url);

        // Append the image to the first paragraph.
       doc.getChild(0).asParagraph().appendInlineImage(resp.getBlob());
    }

}

// replace 3 with sheet.getLastRow()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接