Importing Data from Google Sheets into LO

I am attempting to import data from Google Sheets into my LO Calc sheet.This is the error message I get:

<class 'ModuleNotFoundError'>: No module named 'gspread'
  File "/usr/lib/libreoffice/program/pythonscript.py", line 1057, in getScript
    mod = self.provCtx.getModuleByUrl( fileUri )
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/lib/libreoffice/program/pythonscript.py", line 494, in getModuleByUrl
    exec(code, entry.module.__dict__)
  File "/home/yodap/.config/libreoffice/4/user/Scripts/python/PythonLibray/Weekly_update.py", line 1, in <module>
    import gspread
  File "/usr/lib/python3/dist-packages/uno.py", line 349, in _uno_import
    return _builtin_import(name, *optargs, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Here is my Code:

import gspread
import uno
import json
from oauth2client.service_account import ServiceAccountCredentials

def fetch_data_from_google_sheets():
    # Define the scope
    scope = ["https://spreadsheets.google.com/feeds", "https://www.googleapis.com/auth/spreadsheets",
             "https://www.googleapis.com/auth/drive.file", "https://www.googleapis.com/auth/drive"]

    # Load the credentials from the json key file
    creds = ServiceAccountCredentials.from_json_keyfile_name("xxxxxxxxxx.json", scope)

    # Authorize the clientsheet
    client = gspread.authorize(creds)

    # Get the instance of the Spreadsheet
    spreadsheet = client.open("Portfolio")

    # Get the worksheet by name
    worksheet = spreadsheet.worksheet("Inputs")

    # Get all values
    values = worksheet.get_all_values()
    
    return values

def import_into_calc(*_):
    # Fetch data from Google Sheets
    raw_data = fetch_data_from_google_sheets()

    # Get the current document instead of loading a new one
    desktop = XSCRIPTCONTEXT.getDesktop()
    document = desktop.getCurrentComponent()

    # Make sure we're operating on a spreadsheet
    if not hasattr(document, "Sheets"):
        raise Exception("This script must be run from a LibreOffice Calc document.")

    inputsheet = document.Sheets['Inputsheet']
    start_row_idx = 1  # Start writing from the second row
    max_column_idx = 6  # Write up to column G (0-indexed)

    # Write the data starting from the specified row, only up to the specified column
    for row_idx, row_data in enumerate(raw_data):
        for col_idx in range(max_column_idx + 1):
            value = row_data[col_idx]
            try:
                # Convert to float if possible
                inputsheet.getCellByPosition(col_idx, start_row_idx + row_idx).Value = float(value)
            except ValueError:
                # Leave as a string if not a number
                inputsheet.getCellByPosition(col_idx, start_row_idx + row_idx).String = value.strip()

    print("Data successfully imported into LibreOffice Calc.")

# Expose the main function for use within LibreOffice
g_exportedScripts = import_into_calc,

What am I doing wrong?

probably you need to install gspread from pipy?
open a terminal and type:

pip install gspread --user --upgrade
1 Like

~$ pip install gspread --user --upgrade
error: externally-managed-environment

Ă— This environment is externally managed
╰─> To install Python packages system-wide, try apt install
python3-xyz, where xyz is the package you are trying to
install.

If you wish to install a non-Debian-packaged Python package,
create a virtual environment using python3 -m venv path/to/venv.
Then use path/to/venv/bin/python and path/to/venv/bin/pip. Make
sure you have python3-full installed.

If you wish to install a non-Debian packaged Python application,
it may be easiest to use pipx install xyz, which will manage a
virtual environment for you. Make sure you have pipx installed.

See /usr/share/doc/python3.11/README.venv for more information.

note: If you believe this is a mistake, please contact your Python installation or OS distribution provider. You can override this, at the risk of breaking your Python installation or OS, by passing --break-system-packages.
hint: See PEP 668 for the detailed specification.

sudo apt install python3-gspread
[sudo] password for yodap:
Reading package lists… Done
Building dependency tree… Done
Reading state information… Done
E: Unable to locate package python3-gspread

Am I likely to break anything if I download the tar.gz file gspread …and install it in

/usr/lib/libreoffice/share/Scripts/Python

It would be better if you solve it globally with:

/usr/bin/python -m pip install gspread --user 
1 Like

$ /usr/bin/python -m pip install gspread --user
bash: /usr/bin/python: No such file or directory

so what: your not able to know where youre python interpreter is!!!
you can ask your OS for it:

wich python

or directly:

$(which python) -m pip install gspread --user
1 Like

$ /usr/bin/python3 -m pip install gspread --user
error: externally-managed-environment

Ă— This environment is externally managed
╰─> To install Python packages system-wide, try apt install
python3-xyz, where xyz is the package you are trying to
install.

If you wish to install a non-Debian-packaged Python package,
create a virtual environment using python3 -m venv path/to/venv.
Then use path/to/venv/bin/python and path/to/venv/bin/pip. Make
sure you have python3-full installed.

If you wish to install a non-Debian packaged Python application,
it may be easiest to use pipx install xyz, which will manage a
virtual environment for you. Make sure you have pipx installed.

See /usr/share/doc/python3.11/README.venv for more information.

note: If you believe this is a mistake, please contact your Python installation or OS distribution provider. You can override this, at the risk of breaking your Python installation or OS, by passing --break-system-packages.
hint: See PEP 668 for the detailed specification.

I don’t know what you have tinkered with in your python environment. ( a normal system-wide installed python does not behave so ) but if it is so, then follow this instructions EOT.

1 Like

Thanks for that, but is that virtual environment going to work within LO?

I can’t answer that…I can only guess that an already installed and globally activated Venv is responsible for the current problems?!

1 Like

Thank you for your help, it is much appreciated. I guess I will just have to strip all python related files and folders and LO from my system and reinstall…:frowning: …what a chore. Thanks anyway for the pointer!