Delete this question

Delete - thank you for your help

AI generated ? :innocent:

Yes, full discosure, Chapt GPT helped me…but could not find problem. I asked it for the best way to present the problem for the forum in order to get a resolution… and this is what is suggested!

I’m afraid it’s not :rofl:

I’d suggest you close this post, and retry with a fresh description of the problem you’re trying to address …
" dictionary of file paths " ?? :thinking:
and a bit of your background, like why trying wth macros rather than references ?

If the best way to ask for help is not providing your code, my guess the best solution will be written with invisible ink.
.
So show your code, and use code tags so it is not altered here. And please tell if you wrote the code, or is it also generated by AI.

import uno
import time

def log_error_to_sheet(doc, message, cell_ref="A1"):
    """
    Log messages to the "Diary" sheet of the provided document.
    """
    try:
        diary_sheet = doc.Sheets.getByName("Diary")
        cell = diary_sheet.getCellRangeByName(cell_ref)
        cell.String = message
    except Exception as e:
        print("Failed to log error to sheet:", str(e))

def open_or_get_document(desktop, file_url):
    # Try to retrieve an already opened document by its URL
    components = desktop.getComponents()
    for component in components:
        if hasattr(component, "URL") and component.URL == file_url:
            return component
    # If not found, open a new document
    return desktop.loadComponentFromURL(file_url, "_blank", 0, ())

def copy_data(source_file_path, target_sheet_name, ctx):
    desktop = ctx.ServiceManager.createInstanceWithContext("com.sun.star.frame.Desktop", ctx)
    target_doc = XSCRIPTCONTEXT.getDocument()
    source_uri = uno.systemPathToFileUrl(source_file_path)

    try:
        source_doc = open_or_get_document(desktop, source_uri)
        if not source_doc:
            source_doc = desktop.loadComponentFromURL(source_uri, "_blank", 0, ())
            if not source_doc:
                raise Exception(f"Failed to open {source_file_path}")

        source_sheet = source_doc.Sheets.getByName("Diary")
        vx = source_doc.Sheets.getCount() - 2

        target_sheet = target_doc.Sheets.getByName(target_sheet_name)
        target_sheet.getCellRangeByName("AI1").setString(str(vx))

        source_range_address = f"AK1:CB{vx}"
        source_range = source_sheet.getCellRangeByName(source_range_address)
        source_data = source_range.getDataArray()

        target_range = target_sheet.getCellRangeByName(source_range_address)
        target_range.setDataArray(source_data)

        log_error_to_sheet(target_doc, f"Data copied successfully from {source_range_address} to sheet '{target_sheet_name}'.")
    except Exception as e:
        log_error_to_sheet(target_doc, f"An error occurred while copying data to sheet '{target_sheet_name}': {str(e)}")

def process_file(file_path, sheet_name, ctx):
    # Introduce a delay to give LibreOffice time to open the file
    time.sleep(1)
    copy_data(file_path, sheet_name, ctx)
    # Introduce a delay to give LibreOffice time to process the file
    time.sleep(1)

def main():
    ctx = uno.getComponentContext()

    # Process each file
    process_file("/home/yodap/Documents/Targets/stocks-2x.ods", "2x", ctx)
    process_file("/home/yodap/Documents/Targets/stocks-BRK.ods", "BRK", ctx)
    process_file("/home/yodap/Documents/Targets/stock-3.ods", "3", ctx)
    process_file("/home/yodap/Documents/Targets/stocks.ods", "stocks", ctx)

# Run the main function
main()

I am a beginner with python and got lost in what I was trying to achieve so asked ChatGPT for help…this is what it came up with. It did not work and neither I nor ChatGPT could work out why and it suggested approaching the forum. I asked it how best to present the problem to the forum and what you see is that it suggested.

Sorry I have no idea what you are on about.

:upside_down_face:

…but I managed to solve it myself! Thanks for your help and suggesions.

obvious guess… there exsists no sheet with Name »SheetName« ?!

  1. NO!
  2. show your code!
  3. who knows… but Experience tells: most issues happens on layer 8.
import uno
import time

def log_error_to_sheet(doc, message, cell_ref="A1"):
    """
    Log messages to the "Diary" sheet of the provided document.
    """
    try:
        diary_sheet = doc.Sheets.getByName("Diary")
        cell = diary_sheet.getCellRangeByName(cell_ref)
        cell.String = message
    except Exception as e:
        print("Failed to log error to sheet:", str(e))

def open_or_get_document(desktop, file_url):
    # Try to retrieve an already opened document by its URL
    components = desktop.getComponents()
    for component in components:
        if hasattr(component, "URL") and component.URL == file_url:
            return component
    # If not found, open a new document
    return desktop.loadComponentFromURL(file_url, "_blank", 0, ())

def copy_data(source_file_path, target_sheet_name, ctx):
    desktop = ctx.ServiceManager.createInstanceWithContext("com.sun.star.frame.Desktop", ctx)
    target_doc = XSCRIPTCONTEXT.getDocument()
    source_uri = uno.systemPathToFileUrl(source_file_path)

    try:
        source_doc = open_or_get_document(desktop, source_uri)
        if not source_doc:
            source_doc = desktop.loadComponentFromURL(source_uri, "_blank", 0, ())
            if not source_doc:
                raise Exception(f"Failed to open {source_file_path}")

        source_sheet = source_doc.Sheets.getByName("Diary")
        vx = source_doc.Sheets.getCount() - 2

        target_sheet = target_doc.Sheets.getByName(target_sheet_name)
        target_sheet.getCellRangeByName("AI1").setString(str(vx))

        source_range_address = f"AK1:CB{vx}"
        source_range = source_sheet.getCellRangeByName(source_range_address)
        source_data = source_range.getDataArray()

        target_range = target_sheet.getCellRangeByName(source_range_address)
        target_range.setDataArray(source_data)

        log_error_to_sheet(target_doc, f"Data copied successfully from {source_range_address} to sheet '{target_sheet_name}'.")
    except Exception as e:
        log_error_to_sheet(target_doc, f"An error occurred while copying data to sheet '{target_sheet_name}': {str(e)}")

def process_file(file_path, sheet_name, ctx):
    # Introduce a delay to give LibreOffice time to open the file
    time.sleep(1)
    copy_data(file_path, sheet_name, ctx)
    # Introduce a delay to give LibreOffice time to process the file
    time.sleep(1)

def main():
    ctx = uno.getComponentContext()

    # Process each file
    process_file("/home/Documents/Targets/stocks-2x.ods", "2x", ctx)
    process_file("/home/Documents/Targets/stocks-BRK.ods", "BRK", ctx)
    process_file("/home/Documents/Targets/stock-3.ods", "3", ctx)
    process_file("/home/Documents/Targets/stocks.ods", "stocks", ctx)

# Run the main function
main()


Full disclosure, ChatGPT helped me, but it could not find the error. It suggested (after being asked!) how best to pose the question on the forum to get an answer!

Ignore - no longer and issue I wish to pursue.