Ky -
Ky -

Reputation: 32073

How do I get the current file's name in Google Script?

I want to send automated emails from the script of my spreadsheet. In the title of these, I want the file's name (In this example, "My Workbook", not "Sheet1") in the subject of the email. How do I get the name of the file in/from which the script is running?

enter image description here

I was hoping to get a File object from a SpreadsheetApp object, but it doesn't offer that.

Upvotes: 11

Views: 21194

Answers (3)

0xh8h
0xh8h

Reputation: 3509

This solution works for all types of Google apps files (Docs, Sheets, Forms, ...)

You need to use DriveApp

The below code refers to Form, for instance:

const currentForm = FormApp.getActiveForm()
const formFile = DriveApp.getFileById(currentForm.getId())
const formName = formFile.getName()

Just get the document from the corresponding app, then use DriveApp to get the file by its ID, after that you will have the file name

Upvotes: 2

Akshin Jalilov
Akshin Jalilov

Reputation: 1716

If you want to get the name of the spreadsheet that you are running the script from use:

var name = SpreadsheetApp.getActiveSpreadsheet().getName();

Upvotes: 5

Kriggs
Kriggs

Reputation: 3778

.getActive().getName(); would be pretty effective.

SpreadsheetApp doesn't refer to a specific spreadsheet, you need to specify one then get the name, hence the getActive().

Upvotes: 9

Related Questions