Both spreadsheets and documents have openById()
methods, however they are filetype-specific. If you use DocumentApp.openById()
, it must be given the ID of a google doc, not a spreadsheet.
Here's a utility that can handle both types for you.
/**
* Create a new document or spreadsheet by copying a template, and give editing privileges
* to the given editor.
*
* @param {string} templateId ID of a spreadsheet or google doc, to be used as a template.
* @param {string} filename New file name.
* @param {string} editor (optional) Email address of user to be given editor privileges.
*/
function copyAndShareTemplate(templateId,filename,editor) {
// If no editor provided, assume script owner
var editor = editor || Session.getActiveUser().getEmail();
// Make a copy of given template, as filename
var copy = DriveApp.getFileById(templateId).makeCopy(filename);
// Type-specific handling for spreadsheets & documents
var filetype = copy.getMimeType();
switch (filetype) {
case MimeType.GOOGLE_DOCS:
var document = DocumentApp.openById(copy.getId());
break;
case MimeType.GOOGLE_SHEETS:
document = SpreadsheetApp.openById(copy.getId());
break;
default:
throw new Error( "Unsupported document type." );
}
// Add editing permissions to doc or spreadsheet.
// Note: the addEditor method exists for both.
document.addEditor(editor);
}