Google 文档:如何使用 Google 表格单元格中的 URL 替换图像

时间:2021-03-13 10:01:21

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

请帮我完成脚本。我已经阅读了其他一些文章,但仍然无法正常工作。

主要思想:在 Google 表格中输入数据并运行脚本将这些数据替换到 Google 文档。 (文字和图片)

*** 1. 使用 onOpen() 菜单功能选择行以创建新的 google 文档 *** ✅ (工作中)

*** 2. 替换来自 Google Sheets 数据单元格的文本 *** ✅(工作中)

*** 3. 替换 Google Sheets 数据单元格中的图像 *** ❌(不工作)(我尝试在 Google Sheets 的单元格中使用 URL 和图像,但两者都不起作用) (如果在表格单元格中使用图像,它会在谷歌文档中显示“cellimage”这个词,如果我使用 URL,它只会在谷歌文档中显示 URL)

在这种情况下,我尝试在我的谷歌驱动器中使用 URL 文件 (JPG/PNG)。

如果有更简单的方法请告诉我,请给我一些建议,我真的很感激。我是做脚本的新手。 提前致谢。

这是我的谷歌脚本。

function onOpen() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet(),
    entries = [{
      name: "Generate Document",
      functionName: "main"
    }];
  sheet.addMenu("Generate", entries);
}

var templateFileId = "1oWlXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXbeQA",
  targetFolderId = "1DyEXXXXXXXXXXXXXXXXXXXXXXXXXX4JJa",
  removeFileId = "1RUUXXXXXXXXXXXXXXXXXXXXXXXXXjfi4",
  ss = SpreadsheetApp.getActiveSpreadsheet(),
  sheet = ss.getActiveSheet(),
  lastColumn = sheet.getLastColumn(),
  lastRow = sheet.getLastRow(),
  range = SpreadsheetApp.getActiveSheet().getActiveRange(),
  col = 13, // start with 1
  marks0 = ['#PUR1#', '#PRO1#', '#DATE1#', '#ID1#', '#NAME1#', '#P1#', '#MO1#', '#LOT1#',
    '#SNO1#', '#QTY1#', '#QRID1#', '#QRPRO1#'
  ],
  start = 0, // start with 0
  target = 4;

function main() {
  var values = range.getValues(),
    period = values.length / target,
    rng,
    a;
  for (a = 0; a < period; a++) {
    rng = values.slice(target * a);
    mainn(rng, a);
  }
};

// Duplicate google doc
function createDuplicateDocument(templateFileId, name, a) {
  var source = DriveApp.getFileById(templateFileId),
    newFile = source.makeCopy(name);
  newFile.setOwner("xxxxxxxxxx@hotmail.com");

  var targetFolder = DriveApp.getFolderById(targetFolderId);
  targetFolder.addFile(newFile);

  var removeFile = DriveApp.getFolderById(removeFileId);
  removeFile.removeFile(newFile);

  var n = sheet.getRange(range.getRow() + (target * a), col);
  n.setValue(newFile.getUrl()).setVerticalAlignment("middle");
  n.setWrapStrategy(SpreadsheetApp.WrapStrategy.CLIP);

  return DocumentApp.openById(newFile.getId());
}

// Search a paragraph in the document and replaces it with the generated text
function replaceText(targetDocumentId, keyword, newText) {
  var targetDocument = DocumentApp.openById(targetDocumentId),
    targetBody = targetDocument.getBody();
  targetBody.replaceText(keyword, newText);
  targetDocument.saveAndClose();
}

// Main function to run
function mainn(rng, a) {
  var allDataForDocument0 = rng[0];

  // Check if active range is invalid
  if (allDataForDocument0.length === col) {
    // Create the target file, with whatever name you want
    var date = allDataForDocument0[2].toString().slice(4, 15),
      months = {
        'Jan': '01',
        'Feb': '02',
        'Mar': '03',
        'Apr': '04',
        'May': '05',
        'Jun': '06',
        'Jul': '07',
        'Aug': '08',
        'Sep': '09',
        'Oct': '10',
        'Nov': '11',
        'Dec': '12'
      },
      split = date.split(' ');
    date = [split[1], months[split[0]], split[2]].join('/');

    var newTargetFileName = "PO:" + allDataForDocument0[0] + "  " + date,
      newTargetFile = createDuplicateDocument(templateFileId, newTargetFileName, a),
      newTargetFileId = newTargetFile.getId(),
      len = marks0.length,
      i = 0,
      j = 0,
      dataForDocument = "";

    // For first active range
    for (i = 0; i < len; i++) {
      dataForDocument = allDataForDocument0[i].toString();

      // For every dates you may have to use something like this to ensure a time goes out
      if (marks0[i] === "#DATE1#") {
        dataForDocument = dataForDocument.slice(4, 15);
        months = {
          'Jan': '01',
          'Feb': '02',
          'Mar': '03',
          'Apr': '04',
          'May': '05',
          'Jun': '06',
          'Jul': '07',
          'Aug': '08',
          'Sep': '09',
          'Oct': '10',
          'Nov': '11',
          'Dec': '12'
        };
        split = dataForDocument.split(' ');
        dataForDocument = [split[1], months[split[0]], split[2]].join('/');
      }
      replaceText(newTargetFileId, marks0[i], dataForDocument);
    }

    // For another active range
    for (i = 2; i <= target; i++) {
      var allDataForDocument = rng[i - 1],
        marks = ['#PUR' + i + '#', '#PRO' + i + '#', '#DATE' + i + '#', '#ID' + i + '#', '#NAME' + i + '#', '#P' + i + '#', '#MO' + i + '#', '#LOT' + i + '#',
          '#SNO' + i + '#', '#QTY' + i + '#', '#QRID' + i + '#', '#QRPRO' + i + '#'
        ];
      len = marks.length;
      if (allDataForDocument !== undefined) {
        for (j = 0; j < len; j++) {
          dataForDocument = allDataForDocument[j + start].toString();

          // For every dates you may have to use something like this to ensure a time goes out
          if (marks[j] === "#DATE" + i + "#") {
            dataForDocument = dataForDocument.slice(4, 15);
            months = {
              'Jan': '01',
              'Feb': '02',
              'Mar': '03',
              'Apr': '04',
              'May': '05',
              'Jun': '06',
              'Jul': '07',
              'Aug': '08',
              'Sep': '09',
              'Oct': '10',
              'Nov': '11',
              'Dec': '12'
            };
            split = dataForDocument.split(' ');
            dataForDocument = [split[1], months[split[0]], split[2]].join('/');
          }
          replaceText(newTargetFileId, marks[j], dataForDocument);
        }
      } else {
        for (j = 0; j < len; j++) {
          dataForDocument = ' ';
          replaceText(newTargetFileId, marks[j], dataForDocument);
        }
      }
    }
  }
}

1 个答案:

答案 0 :(得分:1)

这个问题在要点周围有很多杂音,但我建议查看 this 堆栈溢出答案。

如果您想在将图像 url 传递给 DriveApp.getFileById() 之前从图像 url 中提取 id,您可以先使用 this 问题中的某些内容。

相关问题