I am looking for a way to issue SQL queries to a Google Sheet using Python.
I know that Google Sheets has a function called query that can be used to issue SQL queries from within the spreadsheet itself,
https://support.google.com/docs/answer/3093343?hl=en
Is there some way that I can call this function using Python? Maybe through the gspread module?
I expected there to be a way to call Google Sheets functions (like COUNT, SUM and others) using this package.
I am open to trying other methods as well. Basically, I want to query a Google Sheet like a database using Python.
I do not believe there is a direct way to accomplish this using only the Google Sheets API, but I would use pandas and pandasql to accomplish this.
import pandas as pd
import pandasql as psql
.
.
.
# After authenticating with Google Sheets and opening the data-filled sheet
# Get all values from the sheet and store them in a Pandas DataFrame
df = pd.DataFrame(sheet.get_all_records())
# Prepare the query
query = "SELECT * FROM df WHERE ColumnName = 'Value'"
# Execute the query
result = psql.sqldf(query, locals())
# Display the result
print(result)
If you find this answer useful, please vote it up.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With