【问题标题】:Generate Google Docs from a sheet and rename them dynamically从工作表生成 Google Docs 并动态重命名它们
【发布时间】:2020-06-07 19:39:42
【问题描述】:

使用此脚本,我可以首先生成 Google 文档,然后将它们转换为电子表格所有行的 PDF,并使用“文件名”列中的值重命名每个 PDF,然后删除 Google 文档。

我只会生成 Google Docs 而不是 PDF。

(我已经注释了字符串copyFile.setTrashed(true) 以保存Google Doc,但是如何使用“文件名”列重命名它们以及如何避免生成PDF?

守则

var ss = SpreadsheetApp.openById("xxxx").getActiveSheet();
var TEMPLATE_ID = ss.getRange("C2").getValue();
var RESULTS_FOLDER_ID = ss.getRange("D2").getValue();

var PDF_FILE_NAME = ''

var FILE_NAME_COLUMN_NAME = 'File Name'

var EMAIL_COLUMN_NAME = 'Email'

var DATE_FORMAT = 'dd/MM/yyyy';

function createNewDocInFolder(newName, RESULTS_FOLDER_ID) {
  var fileID,fileJson,resource;

  resource = {};
  resource.title = newName;
  resource.mimeType = MimeType.GOOGLE_DOCS;
  resource.parents = [{ id: RESULTS_FOLDER_ID }];

  fileJson = Drive.Files.insert(resource);
  fileID = fileJson.id;//The id of the new Google Doc

  return fileID;
}

function GeneraAttestati() {

  var ui = SpreadsheetApp.getUi();

  if (TEMPLATE_ID === '') {    
    ui.alert('TEMPLATE_ID needs to be defined in code.gs')
    return
  }

  var templateFile = DriveApp.getFileById(TEMPLATE_ID)
  var activeSheet = SpreadsheetApp.getActiveSheet()
  var allRows = activeSheet.getDataRange().getValues()
  var headerRow = allRows.shift()
  var copyFile = templateFile.makeCopy();
  var copyId = copyFile.getId()
  var copyDoc = DocumentApp.openById(copyId);
  var copyBody = copyDoc.getBody();
  var numberOfColumns = headerRow.length;

  allRows.forEach(function(row) {

    function makeDoc(copyBody, headerRow, activeRow, numberOfColumns) {

      var body,
          contentAsTxt,
          newName,
          newDocFileID,
          newDoc,
          headerValue,
          activeCell,
          ID = null,
          recipient = null,
          copyFile,
          columnIndex;

      for (columnIndex = 0; columnIndex < numberOfColumns; columnIndex++) {

        headerValue = headerRow[columnIndex]
        activeCell = activeRow[columnIndex]
        activeCell = formatCell(activeCell);

        copyBody.replaceText('%' + headerValue + '%', activeCell)

        if (headerValue === FILE_NAME_COLUMN_NAME) {

          ID = activeCell

        } else if (headerValue === EMAIL_COLUMN_NAME) {

          recipient = activeCell
        }
      }

      contentAsTxt = copyBody.getText();
      newName = PDF_FILE_NAME !== '' ? PDF_FILE_NAME : ID;

      if (RESULTS_FOLDER_ID !== '') {
        newDocFileID = createNewDocInFolder(newName,RESULTS_FOLDER_ID);// Create the DOC file in the results folder
      }

      newDoc = DocumentApp.openById(newDocFileID);
      body = newDoc.getBody();
      body.setText(contentAsTxt);
      newDoc.saveAndClose();
    }

    makeDoc(copyBody, headerRow, row, numberOfColumns);

  })

  ui.alert('New DOC files created')

  return

  function formatCell(value) {

    var newValue = value;

    if (newValue instanceof Date) {

      newValue = Utilities.formatDate(
        value, 
        Session.getScriptTimeZone(), 
        DATE_FORMAT);

    } else if (typeof value === 'number') {

      newValue = Math.round(value * 100) / 100
    }

    return newValue;

  }

}

【问题讨论】:

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


    【解决方案1】:

    执行此操作的唯一方法是使用高级驱动器服务。您必须从代码编辑器、“资源”菜单和“高级 Google 服务”中启用它

    一些变量被移出循环,然后被传入,以避免在每次迭代中一遍又一遍地重新分配相同的值。

    var EMAIL_COLUMN_NAME = 'Email',DATE_FORMAT = 'dd/MM/yyyy';
    
    function createNewDocInFolder(newName, RESULTS_FOLDER_ID) {
      var fileID,fileJson,resource;
    
      resource = {};
      resource.title = newName;
      resource.mimeType = MimeType.GOOGLE_DOCS;
      resource.parents = [{ id: RESULTS_FOLDER_ID }];
    
      fileJson = Drive.Files.insert(resource);
      fileID = fileJson.id;//The id of the new Google Doc
    
      return fileID;
    }
    
    function GeneraAttestati() {
    
      var ui = SpreadsheetApp.getUi();
    
      if (TEMPLATE_ID === '') {    
        ui.alert('TEMPLATE_ID needs to be defined in code.gs')
        return
      }
    
      var templateFile = DriveApp.getFileById(TEMPLATE_ID)
      var activeSheet = SpreadsheetApp.getActiveSheet()
      var allRows = activeSheet.getDataRange().getValues()
      var headerRow = allRows.shift()
      var copyFile = templateFile.makeCopy();
      var copyId = copyFile.getId()
      var copyDoc = DocumentApp.openById(copyId);
      var copyBody = copyDoc.getBody();
      var numberOfColumns = headerRow.length;
    
      allRows.forEach(function(row) {
    
        function makeDoc(copyBody, headerRow, activeRow, numberOfColumns) {
    
          var body,
              contentAsTxt,
              newName,
              newDocFileID,
              newDoc,
              headerValue,
              activeCell,
              ID = null,
              recipient = null,
              copyFile,
              columnIndex;
    
          for (columnIndex = 0; columnIndex < numberOfColumns; columnIndex++) {
    
            headerValue = headerRow[columnIndex]
            activeCell = activeRow[columnIndex]
            activeCell = formatCell(activeCell);
    
            copyBody.replaceText('%' + headerValue + '%', activeCell)
    
            if (headerValue === FILE_NAME_COLUMN_NAME) {
    
              ID = activeCell
    
            } else if (headerValue === EMAIL_COLUMN_NAME) {
    
              recipient = activeCell
            }
          }
    
          contentAsTxt = copyBody.getText();
          newName = PDF_FILE_NAME !== '' ? PDF_FILE_NAME : ID;
          Logger.log('newName: ' + newName)
    
          if (RESULTS_FOLDER_ID != '' && newName != '') {
    
    
            newDocFileID = createNewDocInFolder(newName,RESULTS_FOLDER_ID);// Create the DOC file in the results folder
    
    
            newDoc = DocumentApp.openById(newDocFileID);
            body = newDoc.getBody();
            body.setText(contentAsTxt);
            newDoc.saveAndClose();
          }
        }
    
        makeDoc(copyBody, headerRow, row, numberOfColumns);
    
      })
    
      ui.alert('New DOC files created')
    
      return
    
      function formatCell(value) {
    
        var newValue = value;
    
        if (newValue instanceof Date) {
    
          newValue = Utilities.formatDate(
            value, 
            Session.getScriptTimeZone(), 
            DATE_FORMAT);
    
        } else if (typeof value === 'number') {
    
          newValue = Math.round(value * 100) / 100
        }
    
        return newValue;
    
      }
    
    }
    

    【讨论】:

    • 我有这个错误:异常:I parametri (DocumentApp.Body,String) non corrispondono alla firma del metodo per Utilities.newBlob.
    • 我添加了这一行:contentAsTxt = copyBody.getText(); 看看它的作用。
    • 它只生成 PDF 而不是 GDocs。我只会生成 Google Docs 而不是 PDF,现在将它们重命名为 PDF。
    • 无效。这是错误:GoogleJsonResponseException: Chiamata API a drive.files.insert non riuscita con errore: File not found。 (附言我已经用你的编辑更新了整个脚本)
    • 我添加了一些代码来测试有效名称和一些日志。运行代码,然后查看日志。
    猜你喜欢
    • 2017-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-24
    相关资源
    最近更新 更多