从DOC中的表格中的标识单元格中获取图像URL,然后替换为图像



我试图从用户输入(这是位于驱动器中的图像的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

我认为主要问题是您似乎没有调用您的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似乎返回带有一个项目的列表,这就是为什么我采用结果的零索引。

最新更新