在Google文档中自动增加文件名? [英] Autoincrement filename in Google Docs?

查看:136
本文介绍了在Google文档中自动增加文件名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何为所有帐户的文档添加功能,当我打开新文档的文件时,它想找到我现在所在的文件夹+最后一个文件名,并递增1&救.

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.

对于默认名称为未命名文档"的Google Doc保存文档,但我希望将其保存:

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

folder_1.1001.doc
folder_1.1002.doc

,如果我在下一个Folder2中创建文件:

and if I create file in next Folder2:

folder_2.001.doc
folder_2.002.doc.

folder_2.001.doc
folder_2.002.doc.

我的错误代码:

// 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());
  }
}

推荐答案

以下是示例代码:

// 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);
  }
}

参考文献:

  • 文件
  • Document#setName
  • Blob
  • References:

    • File
    • Document#setName
    • Blob
    • 这篇关于在Google文档中自动增加文件名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆