Autoincrement filename in Google Docs?

独自空忆成欢 提交于 2019-12-08 09:16:23

问题


How I can add function to Docs for all my accounts, when I open new doc's file it want find my folder where I now + last filename and increment 1 & save.

For default Google Doc save document with name 'Untitled document', but I want that it save it:

folder_1.1001.doc
folder_1.1002.doc

and if I create file in next Folder2:

folder_2.001.doc
folder_2.002.doc.

My bad code:

// Show current folder name & root folder name
function makeFilename() {

  // Get current folder name
  var ui = DocumentApp.getUi();
  thisFileId = DocumentApp.getActiveDocument().getId();

  var thisFile = DriveApp.getFolderById(thisFileId);
  var parentFolder = thisFile.getParents();
  var currentFolderName = parentFolder.next();
  ui.alert(currentFolderName);

  // get all files in currentFolderName
  var files = parentFolder;
  while (files.hasNext()) {
    var file = files.next();  
   //  Logger.log(file.getName());
   DocumentApp.getUi().alert(file.getName());
  }
}

回答1:


Here's a sample code:

// Show current folder name 
function makeFilename() {

  // Get current file name
  const ui = DocumentApp.getUi(),
    doc = DocumentApp.getActiveDocument(), //Added
    thisFileId = doc.getId(),
    thisFileName = doc.getName();

  const thisFile = DriveApp.getFileById(thisFileId);//Modified from getFolderById
  const parentFolder = thisFile.getParents();
  const currentFolder = parentFolder.next();//Modified from currentFolderName
  const currentFolderName = currentFolder.getName();//Added
  //ui.alert(currentFolderName);

  /*Store a init file in root to getLatestFileNumber*/
  var initIter = DriveApp.getFilesByName(currentFolderName + 'init000'),
    initBool = initIter.hasNext(),
    init;
  if (!initBool) {
    init = DriveApp.createFile(currentFolderName + 'init000', '0');
  } else {
    init = initIter.next();
  }

  /*Get current Number and format it to 4 digits*/
  var currentNum = init.getBlob().getDataAsString() * 1 + 1,
    formatNum = ('00000' + currentNum).substr(-4);

  /*If filename already contains folderName, do nothing*/
  if (!(thisFileName.search(currentFolderName) + 1)) {
    doc.setName(currentFolderName + formatNum).saveAndClose();
    init.setContent(currentNum);
  }
}

References:

  • File
  • Document#setName
  • Blob


来源:https://stackoverflow.com/questions/52050887/autoincrement-filename-in-google-docs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!