Chapter 1:
Connect a Google Sheet to your Anvil app

To start off, we’ll create a new app using Anvil’s drag-and-drop editor and link it to a Google Sheet with some sample data in. Then we’ll demonstrate how you can access that Sheet from inside the app.

Step 1: Create an app

Log in to Anvil and click ‘New Blank App’.

Location of the Create App button

Choose the Material Design theme.

Select Material Design theme

Step 2: Add the Google API service

In the panel on the left (the App Browser), click the ‘+’ next to ‘Services’:

Adding Google service

Then select the Google service:

Adding Google service

Step 3: Connect your Google Sheet

Copy this Sheets file to your own Google Drive folder.

In Anvil’s Google Drive File Dialog (under ‘Services’ in the App Browser), click “Add app file”.

Add app file

Select your Google Sheet and add it in ‘read’ mode. This means your app will be able to read the contents of the Sheet but not modify it.

Client can read but not write the Sheet

Step 4: Go to the Code view

Go to ‘Code’ view in the Form Editor:

The location of code view in the Anvil Editor

This is where you will write your client-side Python code that runs in the browser.

Step 5: Import your Sheet

To use your Google Sheet in the app code, you need to load it. Import the files like this:

from anvil.google.drive import app_files

Each file is accessed using a version of its name with any spaces joined by underscores. In this case, since our file is called ‘My Library’ we access it by calling app_files.my_library

Step 6: Use your Sheet

In the Form code, add these lines:

lib = app_files.my_library
print("File is called: " + lib.title)
self.worksheet = lib[0]
print(self.worksheet.fields)

Now click the ‘Run’ button in the top right corner to run the app. You’ll see the results print out in the App Console log.

The fields from the 0th worksheet in your Sheet appear in the log

Here is how it should look when you click ‘Run’:

The fields from the 0th worksheet in your Sheet appear in the log

What does this code do? First, it accesses the Google Sheet we connected earlier. lib = app_files.my_library

Next, we make a new variable, self.worksheet pointing at the first page of the Google Sheet. If a Google Sheet has multiple pages, you can access each one in turn by selecting lib[0], lib[1], lib[2] and so on.

Then it prints a list of each of the titles of the columns of that page. In our case these fields are

['ISBN', 'Title', 'Description', 'Authors', 'Publisher', 'Published', 'Pages', 'Language']

We’ve now built a basic app and connected a Google Sheet to it. We can even print out the column headings of the Sheet inside Anvil, to show our app can access the contents of the Sheet.

We’re off to a good start! Time for Chapter 2.

Chapter complete

Congratulations, you've completed this chapter!