从“文档”表中的“标识的”单元格获取图像URL并替换为图像

时间:2018-12-19 16:38:09

标签: google-apps-script

我正在尝试从用户输入中添加图像(这是位于其驱动器中的图像的URL)。确定图像ID后,我可以追加和替换URL,但是我似乎无法在代码中将ID与URL隔离开来。

function getMyImage() {
  var ui = DocumentApp.getUi();
  //Creates a prompt for the user so that the row with keys can be found
  var response = ui.prompt('In what row are the pictures or links found? (Please indicate a number)');
  //Converts response to int and removes one to fit indexing 
  var rowNum = response.getResponseText() - 1

  var doc = DocumentApp.getActiveDocument();
  var body = doc.getBody();
  //Gets all tables in document
  var tables = body.getTables();
  //Passes through each table
  for (var i = 0; i < tables.length; i++){
    //Using this cell in particular determined by prompt result and 1, since DocAppener
    var idCell = tables[i].getRow(rowNum).getCell(1);
    //**Up to here everything works**

    var url = idCell.getText();
    function getIdFromUrl(url) { 
      return url.match(/[-\w]{25,}/); 
    }  
    //Find the image
    var image = DriveApp.getFileById(url)

    //**Past here everything works** 

    //Remove the text in the cell and replace it with image
    var appendedImage = idCell.clear().appendImage(image.getBlob());
    //Set height and width to create a standard for all images
    var iHeight = appendedImage.getHeight()
    var Ratio = iHeight/300
    var iWidth = appendedImage.getWidth()/Ratio
    //Calling height and width as well as set url
    appendedImage.setHeight(300).setWidth(iWidth).setLinkUrl(imageurl)}
}

这是我所讨论的文档。 https://docs.google.com/document/d/1FfzIm9GFhftgsTp7ZEd2l7ZywGVn0yVWZHaQFTUdHvk/edit?usp=sharing

1 个答案:

答案 0 :(得分:1)

我认为主要的问题是您似乎没有调用getIdFromUrl函数,而只是调用了DriveApp.getFileById(url)

我认为您想这样做:

var url = idCell.getText();
function getIdFromUrl(url) { 
  return url.match(/[-\w]{25,}/); 
}

var id = getIdFromUrl(url)[0];  // <-- Add this

//Find the image
var image = DriveApp.getFileById(id)  // <-- Get id

getIdFromUrl似乎返回一个包含一项的列表,这就是为什么我将结果的索引设为零。