Google Sheets Program

Step 1: Set Up Your Workspace

  1. Create a project folder
  2. Inside the folder:
    • Create your main Python script (e.g., run.py)
    • Create a .gitignore file (to exclude sensitive files from version control)

Step 2: Get Google Sheets API Credentials

  1. Go to the Google Cloud Console
  2. Create a project and enable:
    • Google Sheets API
    • Google Drive API
  3. Create Service Account Credentials
  4. Download the JSON credentials file
  5. Move the JSON file into your project's root directory and rename it to creds.json
  6. Open creds.json and copy the value of "client_email"
  7. On your Google Sheet:
    • Click Share
    • Paste the copied email into the share field
    • Select Editor access
    • Untick Notify people
    • Click Share

Step 3: Keep Credentials Private

Edit your .gitignore file and add creds.json

This prevents the credentials from being pushed to GitHub or any version control system.

Step 4: Install Required Libraries

Open your terminal and run the following to install the libraries required to access and modify your Google Sheet.

pip3 install gspread google-auth

Step 5: Set Up Your Python File

Start with the necessary imports

import gspread
from google.oauth2.service_account import Credentials

Define your scope and authorize the client:

SCOPE = [
    "https://www.googleapis.com/auth/spreadsheets",
    "https://www.googleapis.com/auth/drive.file",
    "https://www.googleapis.com/auth/drive"
]

CREDS = Credentials.from_service_account_file('creds.json')
SCOPED_CREDS = CREDS.with_scopes(SCOPE)
GSPREAD_CLIENT = gspread.authorize(SCOPED_CREDS)

SHEET = GSPREAD_CLIENT.open('file_name')

Step 6: Get and Validate User Data

Define a function to get e.g. sales data:

def get_sales_data():
    """
    Get input from the user for sales data,
    split the string into a list, and validate it.
    """
    while True:
        print("Please enter sales data from the last market.")
        print("Data should be six numbers, separated by commas.")
        print("Example: 10,20,30,40,50,60\n")

        data_str = input("Enter your data here: ")

        sales_data = data_str.split(",")

        if validate_data(sales_data):
            print("Data is valid!")
            break

    return [int(num) for num in sales_data]

Define a separate validation function:

def validate_data(values):
    """
    Validates that exactly six integers were entered.
    Returns True if valid, False otherwise.
    """
    try:
        if len(values) != 6:
            raise ValueError(
                f"Exactly 6 values required, you provided {len(values)}"
            )
        [int(value) for value in values]
    except ValueError as e:
        print(f"Invalid data: {e}. Please try again.\n")
        return False

    return True

Step 7: Update the Worksheet

Define a function to send data to a worksheet:

def update_worksheet(data, worksheet):
    """
    Receives a list of integers and a worksheet name,
    then appends the data to that worksheet.
    """
    print(f"Updating {worksheet} worksheet...\n")
    worksheet_to_update = SHEET.worksheet(worksheet)
    worksheet_to_update.append_row(data)
    print(f"{worksheet} worksheet updated successfully!\n")

Step 8: Tidying Up with a Main Function

Organize your code with a main() function that calls everything:

def main():
    data = get_sales_data()
    update_worksheet(data, "sales")

main()