1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

[Python] Updating Excel files with Python

Discussão em 'Python' iniciado por Stack, Maio 8, 2025.

  1. Stack

    Stack Membro Participativo

    I want to update the excel files in the Cn folder on the desktop. There is an Autoopen command in excel files. When the file is opened, if the conditions are suitable, it updates and closes it. I wanted to have a python code that opens these files in alphabetical order for the night hours when the conditions are completely suitable, waits until the update is finished and moves on to the next file after the file closes itself. I also wanted to create a .bat file to trigger this python file and trigger this .bat file with the windows task scheduler. But no action happens. What is the problem?

    Python code :

    import os
    import time
    import win32com.client

    # Define the path to the 'Cn' folder on the desktop
    folder_path = os.path.join(os.path.expanduser("~/Desktop"), "Cn")

    # Start the Excel application (in background)
    excel = win32com.client.Dispatch("Excel.Application")
    excel.Visible = True # Set to False if you want it hidden

    # Get Excel files in alphabetical order
    files = sorted(
    f for f in os.listdir(folder_path)
    if f.lower().endswith((".xlsm", ".xlsb", ".xlsx", ".xls"))
    )

    # Open each file in order, wait for update to finish, then move to the next
    for file in files:
    full_path = os.path.join(folder_path, file)
    print(f"Opening: {file}")

    try:
    wb = excel.Workbooks.Open(full_path)

    # Wait until the AutoOpen process finishes and the file closes itself
    while True:
    time.sleep(1)
    if wb.Name not in [w.Name for w in excel.Workbooks]:
    print(f"Closed: {file}")
    break

    except Exception as e:
    print(f"Error occurred ({file}): {e}")

    # Quit Excel after all files are processed
    excel.Quit()


    .bat code

    @echo off
    cd /d "C:\Users\****\Desktop\Cn"
    "C:\Users\****\AppData\Local\Programs\Python\Python313\python.exe" cn_excel_ac.py

    Continue reading...

Compartilhe esta Página