Skip to Main Content
University of York Library
Library Subject Guides

Essential Apps Script: a Practical Guide

2: Creating documents

Section 2: Creating documents

In the second part of the course, we will explore how to create and edit documents, as well as splitting code into multiple functions.

Work through the page in order if you're learning, or use the links below to jump to specific bits:

Troubleshooting Apps Script code

Now that you've done some livecoding and had a go at the first project, you might have started to notice some of the common ways Apps Script can go wrong. Don't worry, it happens to everyone! Error messages and troubleshooting why your Apps Script code didn't work as expected are all part of the process.

Here are some useful pointers for troubleshooting issues with your Apps Script code:

  • Read error messages - If your script isn't working and there's an error message either in the Editor or in the Execution Log, read it! There can be helpful information about the kind of error that has occured and on which line the computer thinks it has happened (but bear in mind sometimes this is a symptom of the real error being on an earlier line, breaking something further down).
  • Check your syntax - Spelling and punctuation are vitual in Apps Script. Common errors include using incorrect punctuation, misspelling commands or variable names, and missing off brackets where needed. Asking someone else to take a look at your code if they also know Apps Script can be useful for spotting tiny errors like this.
  • Get the right order - Computers read code from top to bottom, so sometimes errors can occur because your code is in the wrong order. For example, you can't use variables you've not already created, so make sure you create them before you use them!

You'll probably want to look online for support when you're having issues with Apps Script. The Apps Script Developer Reference is a useful starting point for checking what particular Apps Script commands do. When searching online, try using text from the error message or the syntax of the command you're trying to use in your search. Even if you don't understand every word of people's suggestions, you might find something to try or get a new idea about what to tweak in your code.

Introduction to documents and files

In this section, we're going to be working with Google Docs documents, but to do this, we need to look at the difference between a document and a file in the world of Apps Script.

In Apps Script, we can use document and file to mean specific things. Sometimes with Google items like spreadsheets, documents, and presentations, you need to access specific commands relating to the type of content it is, like we saw in the previous section with working with spreadsheets. To do this, we need to use the specific app built into Apps Script to work with this content, like the SpreadsheetApp or the DocumentApp. So if we are working with a document, we are working with the DocumentApp to access features like the body of the document, the font, formatting, and other elements.

In contrast, we might be working with any type of item on Google Drive and only using features that could be done with any kind of item (so it doesn't matter if it is a spreadsheet, a document, etc). For example, if you want to copy a file or change the sharing permissions, this can be done through Google Drive and it doesn't matter what kind of item it is. In this case, we can use the DriveApp and we can refer to the item as a file, as it doesn't matter what kind of file it is.

This may seem like an arbitrary distinction, but it helps us to know which App we need to use within Apps Script and which commands we might find. We'll be using files and documents (and the DriveApp and the DocumentApp) in this section of the course.

Calling another function

Very long Apps Script code in a single function can be difficult to work with, as there's a lot of code doing a range of different things at once, and that code has to be repeated if you need to do the same action in different places in the code. That's where splitting your Apps Script project into multiple functions can be useful.

By default your Apps Script code is within a single function. Creating several separate functions allows you to more easily reuse parts of your code in different places in your project, as well as making it much easier to read and edit specific parts of your project. For example, you could have a function that creates a document from a template and that could be used to create a single document at one point in the project and many documents from a dataset at another point.

When you have multiple functions, what you need is a main function that will run when you press the Run button (or use a menu item or a trigger), and any other functions will be called in the main function, which means you write the name of the function in the code and then it will run at that point.

When you call another function, you can pass values to it, like variables, so that other function can use those values as needed. Values created in this other function can be returned to the main function, so you could create a document in another function and then pass back the URL or ID to the main function.

Example of using multiple functions

In the example diagram below, the main function is getSpreadsheetData(). It gets data from a spreadsheet and gets a file ID stored in that data. It passes the file ID to another function createDocument() which makes a copy of that file and returns the URL of this new copy to the function getSpreadsheetData(). The code in getSpreadsheetData() could then go on to do things with this document, like change its content.

Write a function name in another function to call that function so it runs, and you can return values from that other function to the main one using the command return

Livecoding 3: calling functions

In this livecoding exercise, we're going to have a go at writing two functions, calling one function from another, and sending a variable from one function to the other.

Copying files

In Apps Script, it can be very useful to be able to make copies of template documents that you can put into particular folders, prefill with information, and/or share with certain people. This is easier than creating documents from scratch and formatting them with Apps Script, as you can use Google Docs to set up your document's structure rather than having to try and do it all using code. You can also add placeholders for any content you want to replace with data using Apps Script.

Tip

When making copies, you are working with a file as copying is something you can do from Google Drive, so use the DriveApp. This means you can make copies of other kinds of files, not just Google Docs documents.

To copy a file, you need its ID, as well as the ID of a destination folder. You then need to get the file and folder, and then make a copy of the file. Let's take a look at how to do this.

Getting files and folders by ID

In the world of Google apps, the ID of a file or folder is the string of characters in the URL, usually after or between forward slashes. For a file there can be other content in the URL after the ID, like "/edit" but folders typically end with the ID. Don't include any of the forward slashes when copying an ID.

The ID of a Google file is just the string of random characters at the end of the URL, after a forward slash

Once you've copied the ID of a file or folder, you can paste it either directly into a command, or you can save it as a variable with a sensible name like "templateID" or "folderID" first and then use the variable as needed. The latter method can be useful as you can put the ID at the top of your code, making it easy to change if you change the folder or template file. Don't forget that it is a string, so the ID will need to be surrounded by single or double quote marks.

var fileID = '1RtVtXhHXVOvmJ6d0B073BFGhEcXPlZSFQPKc5a0Ocnc';

To get a file or folder now we have the ID, we get use the DriveApp to access the commands getFileById and getFolderById. Be careful with the capitalisation there - it won't work if you write 'ID' instead of 'Id'.

var template = DriveApp.getFileById(id_of_template_file);

var destinationFolder = DriveApp.getFolderById(id_of_folder);

Copying a file

Once you've got the template file and the folder stored in variables, you can copy the template using the makeCopy command. You will also need to give the file a name at this point, which you can either create inside the brackets or store in a variable beforehand.

template.makeCopy("My File Name", destinationFolder);

// alternate option
var filename = "My File Name";
template.makeCopy(filename, destinationFolder);

You will typically need either the URL or the ID of the new document, so usually what you would want to do instead of the above code is use the following code and store the result in a variable:

// Version to get URL
var newDocUrl = template.makeCopy(filename, destinationFolder).getUrl();

// Version to get ID
var newDocId = template.makeCopy(filename, destinationFolder).getUrl();
Tip

Though this example shows getting both the URL and the ID when copying a file, do not use both versions at once like this, as you would make two different copies of your file!

Livecoding 4: copying a file

In this livecoding exercise, we will be copying a template file into a particular folder.

Editing documents

To edit Google Docs documents using Apps Script, you need to first open the file using a command like openById or openByUrl and then you can target parts of the document to edit.

A document is made up of several parts. Once you have a document open using Apps Script, you can get the body, containing most of the content of the document, and you can also get things like the header, bookmarks, footnotes, and footer. If you want to be able to add or edit text in a document or create other things like tables, you will need to first get the body of the document using getBody and then you can use commands like appendParagraph and replaceText to work with the text content in the document.

Let's take a look at these methods for editing documents in more depth.

Opening a document

To open an existing document (either one you've just created, or one that already existed before the code ran), you can use its ID or URL (as we looked at under Getting files and folders by ID). You use the corresponding app for the kind of file it is, so for documents you use the DocumentApp and then the openById() or openByUrl() command. These both work identically, so it depends on what you've already got stored in your code (or not) as to whether you use the ID or URL option.

You will typically store the file in a variable once it is opened, so your code will be something like:

var document = DocumentApp.openById(docID);

var otherDocument = DocumentApp.openByUrl(otherDocUrl);
Tip

Remember that you have to open and store in a variable any document, spreadsheet, or other file to work with it in Apps Script, as you can then use the variable to access commands relavant to that app.

Getting the body

Once you open a document, you have to get the document body to be able to edit or add content to it using the getBody() command with the document you've already opened. Typically this means that you would store the document body in its own variable.

var documentBody = document.getBody();

Appending text

If you just want to add more content to the bottom of a document, you can use appendParagraph() to add paragraphs below the last item in the body of the document.

You can include the content you want to add within the brackets of the expression, but it can be easier to set it up as a variable first and then use that.

var paragraphContent = 'Little Miss Muffet sat on her tuffet';
documentBody.appendParagraph(paragraphContent);
document.appendParagraph('Eating her curds and whey');

Replacing text (find and replace)

When working with documents in Apps Script, changing text within the body can be done using replaceText(), which finds particular text in the document and replaces it with a given string. This is particular useful for templates, as you can create placeholders and then replace these with data, e.g. from a spreadsheet or form.

Tip

Make sure that your placeholders are unique (if they need to be) and distinctive. One option is to use symbols like << >> around your placeholder word(s) so you know it won't be elsewhere in the document and accidentally replaced as well!

replaceText() needs two pieces of information: the text to find (as a string) and the text to replace it with (as a string). You can put these directly into the command or use variables. One common use for these is to replace values from a dataset, so you might have a '<>' placeholder that is replaced with a name from a dataset stored in a variable.

documentBody.replaceText('<<name>>', 'Mickey');

documentBody.replaceText('<<name>>', studentName);

Livecoding 5: editing documents

In this livecoding exercise, we're going to edit a document we've created by replacing placeholders with other text.

Livecoding 6: ongoing project part 2

Now, we are going to return to our ongoing livecoding project that we started in section 1. You can work in the same file as that one, or make a copy of that file and work in the copy so you still have the original from the first section stored in your Drive as well.

To extend our project, we are going to add in creating a document and replacing some text in it.

Essential Apps Script project 2

Now that we've reached the end of section 2, we have another project for you to have a go at. Once again, we recommend that you try this project before moving on to section 3, as this helps you to consolidate your knowledge about working with documents and practice writing Apps Script code yourself.

For Project 2, you will be creating a system that can generate individual Google docs for rows on a spreadsheet containing (fake) module results. The user should be able to select a row and generate the document for that data. It brings together things from sections 1 and 2, so do look back at the information and livecoding from both weeks as you work through it.

Start with the guidance document. It is more brief than the first project, but still has all the information you'll need to create the project. If you get stuck, you can always access the solution file to take a look at one possible solution - again, you'll need to make a copy of this file to see the Apps Script project and compare your code.

Feedback
X