Home > Software design >  Saving files to google drive automatically in a folder based on a name in the file (Invoice System)
Saving files to google drive automatically in a folder based on a name in the file (Invoice System)

Time:11-26

I am creating an invoice system and I am wanting to save the pdfs to google drive.

I set it up so that they would just all save to the same folder. Then I realized that I could make a folder for each individual customer. And by having the script pull the folder ID off of the Client List tab. (See it on column Q of sheet under Client List Tab)

However this means manually making a folder and doing for each new customer. So ideally the script would save each PDF to its own folder based on the name of the customer and create a new folder if there is no folder for that customer.

Is that possible? If so, any pointers to do so? Thanks!

Link for spreadsheet https://docs.google.com/spreadsheets/d/1i3CXHR_EBal5_JAcoKKopNovySzvhmKVCVXXD7K9ke4/edit?usp=sharing

CodePudding user response:

Assuming you have the client name in variable clientName:

const clients = SpreadsheetApp.getSheetByName('Client List').getDataRange().getValues();
const folders = {};
for (let i = 6; i < clients.length; i  ) {
  folders[clients[i][0]] = clients[i][16];
}
let folder;
const id = folders[clientName];
if (id) { folder = getFolderByIdDriveApp.getFolderById(id); }
else { folder = parentFolder.createFolder(clientName); }

CodePudding user response:

You code can easily handle this.

I am going to assume that you have the customer number. The first thing your code should do would be to do a file.list and using the Q parm as you menotned search for a file with the name of customerNumber and the mime type of application/vnd.google-apps.folder This will give you the file id of that folder.

If it does not exist then you can do a file.create and set the mime type again to 'application/vnd.google-apps.folder'. This response will return you a file id.

Now you have the file id you can upload your file, and set parents to the file id that you just created.

When uploaded your file will be in the directory for that customer.

It is potentially a three step process but it will work.

However this means manually making a folder and doing for each new customer. So ideally the script would save each PDF to its own folder based on the name of the customer and create a new folder if there is no folder for that customer.

  • Related