如何从电子表格中获取“单元格中的图像”并将其作为INLINE_IMAGE复制到文档中?

时间:2019-06-09 15:54:16

标签: google-apps-script google-sheets

我已经将电子表格设置为DB,以存储类似目录的信息。此信息的重要元素是最终用户使用Google Spreadsheet的菜单选项“插入->图像->单元格中的图像”将其插入到用户面板中的图像。然后使用脚本中的“ SpreadsheetApp.CopyPasteType.PASTE_VALUES”将此图像复制到存储表中。

现在,我正在设计一个文档,作为存储在DB中的信息的输出。问题是我无法将电子表格中的图像解析为文档。我什至无法从电子表格中获取它。

我已经在网上冲浪寻找解决方案,但一无所获。我发现的最接近的问题是一个已有2年历史的类似问题,没有直接回答:how to copy IMAGE from a google spreadsheet to a google document in script?

我的逻辑说,如果我将单元格内的图像粘贴为一个值,则应该可以使用.getValue()将其取回,但显然并非如此。我试图把它当做运气不好的东西。我对blob不太熟悉,所以我可能做错了。

任何想法将不胜感激:)

// This is the code I used to put the image in the cell (THIS WORKS, JUST FOR CONTEXT)
  var fotosToCopy = cotizador.getRangeByName('CotizacionFotos');
  fotosToCopy.copyTo(destino.getRange(fila,2), 
  SpreadsheetApp.CopyPasteType.PASTE_VALUES, true);

// This is the code I'm trying to get the image from the cell (NOT WORKING)
  var fotosToCopy = origen.getRange(personajeRow,2).getValue(); //I've tried .getFormula() with no results; origen is the search range, personajeRow is the row to do the search and both work.

// This is what I'm using to put the image in the document
  var doc = DocumentApp.openById(cotizacionId); // cotizacionId is working
  var body = doc.getBody();
  var foto = body.getImages(); // I'll replace the only existing image
  var parent = foto[0].getParent();
  parent.insertInlineImage(parent.getChildIndex(foto)+1, fotosToCopy[0]); //fotosToCopy[0] is the issue, it returns "undefined"
  foto[0].removeFromParent();

理想情况下,文档中现有的嵌入式图像应替换为电子表格中的单元内图像。我得到的错误是:“执行失败:无法将数组转换为元素”。

有什么主意吗?

1 个答案:

答案 0 :(得分:0)

所以我还没有很清楚地编写代码,但是它应该给您一些您想要的东西,但首先要说明一下:

Google表格无法返回图片的Blob,只能返回对图片的引用,而Google云端硬盘无法返回。

下面我的解决方案将Google云端硬盘文件夹中FIRST图片的Blob放入并根据我提供给函数的DocID将其添加到文档中:

function retriveFolder(folderName,imageName,docID){

  var imageFolder = DriveApp.getFoldersByName(folderName).next();

  var firstImageinFolder = imageFolder.getFilesByName(imageName).next();

  var imageBlob =  firstImageinFolder.getBlob();

  DocumentApp.openById(docID).getBody().insertImage(1, imageBlob);

}

我希望这会有所帮助,当我遇到相同的问题时,最好能提出我的建议。不太理想,但是应该是一个适当的解决方法。