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 2: Add the Google API service
In the left panel (the App Browser), click the + next to Services:
Then select the Google API service:
Step 3: Connect your Google Sheet
Copy this Sheets file to your own Google Drive folder. It contains a worksheet called Transactions with four columns: Date, Amount, Category, and Note. We’ve pre-filled it with sample data so you have something to work with straight away.
In Anvil’s Google Drive File Dialog (under Services in the App Browser), click Add files from Google Drive to this app. You may be prompted to sign in to Google and give Anvil permission to access your Drive.
Select your Google Sheet and add it to your app.
my_finance_tracker, click the pencil icon next to the file name in the App Browser to rename it.Step 4: Go to the Code view
Go to the Code view of Form1 in the Form Editor:
This is where you will write your client-side Python code that runs in the browser.
Step 5: Use your Sheet
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 Finance Tracker we access it by calling app_files.my_finance_tracker.
In the Form code, add these lines to the __init__ method:
tracker = app_files.my_finance_tracker
print("File is called: " + tracker.title)
self.worksheet = tracker[0] # Access the first worksheet in the Sheet
print(self.worksheet.fields)from anvil.google.drive import app_files at the top of your Form, add it manually.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.
What does this code do? First, it accesses the Google Sheet we connected earlier.
tracker = app_files.my_finance_trackerNext, 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 tracker[0], tracker[1], tracker[2] and so on. Then it prints the column headings to confirm our app can read the Sheet correctly.
We’ve now built a basic app and connected a Google Sheet to it. We even printed 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.
By