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’.
Choose the Material Design theme.
Step 2: Add the Google API service
In the panel on the left (the App Browser), click the ‘+’ next to ‘Services’:
Then select the 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”.
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.
Step 4: Go to the Code view
Go to ‘Code’ view in the Form 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
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 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.
Here is how it should look when you click ‘Run’:
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 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.