问题
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