Different behaviour between win 10 and win 11 of a python script

The following code works differetly between two PC with identical PY version 3.11.9, identical libraries installed and identical source folder files.

The aim is to open every single excel file in a specified folder, add a line to the first page inserting a specified text and print all sheets but not the first one. all this repeated 4 times per file with different text every time. in win 11 everithing is fine, but on win 10 seems that excel is not closed properly to each cycle so the result is print only the first 4 times with the last one with 4 lines added with all texts. someone can explain me why?

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import os
import re
import win32com.client # type: ignore
import tkinter as tk
from tkinter import messagebox, Radiobutton, Entry, Label, Button, IntVar, ttk
# Costanti per gli stili di bordo di Excel e il formato di carta
xlEdgeBottom = 9
xlContinuous = 1
xlPaperA4 = 9 # Formato carta A4
xlLandscape = 2 # Orientamento orizzontale
# Testi per le intestazioni delle 4 copie di stampa
testi_intestazioni = [
"Text 1",
"Text 2",
"Text 3",
"Text 4"
]
def get_sort_key(filename):
days = {'LU': 1, 'MA': 2, 'ME': 3, 'GI': 4, 'VE': 5} # Mappa i giorni a valori numerici
parts = filename.split('_')
week = int(parts[-2])
day = days.get(parts[-1].split('.')[0], 0)
return (week, day)
def printmanager(cartella, week_filter=None, day_filter=None):
excel = win32com.client.Dispatch("Excel.Application")
excel.Visible = False # Imposta Excel non visibile durante l'esecuzione
try:
files_to_print = [f for f in os.listdir(cartella) if f.endswith(('.xls', '.xlsx'))]
files_to_print.sort(key=get_sort_key)
files_printed = 0 # Contatore per tracciare il numero di file stampati
for filename in files_to_print:
# Creazione di un pattern di ricerca per la settimana che isola esattamente il numero inserito
if week_filter:
week_pattern = fr'WK_{week_filter}_' # Assicura che il pattern includa W seguito dalla settimana e underscore
if not re.search(week_pattern, filename):
continue
if day_filter:
# Assumi che i giorni siano indicati nel filename con _LU, _MA, ecc.
day_pattern = f'_{day_filter}'
if day_pattern not in filename:
continue
full_path = os.path.join(cartella, filename)
workbook = excel.Workbooks.Open(full_path)
for i in range(4):
workbook.Sheets(1).Copy(After=workbook.Sheets(1))
copied_worksheet = workbook.Sheets(2)
copied_worksheet.Rows("1:1").Insert()
copied_worksheet.Columns("Z:Z").Hidden = True
copied_worksheet.Columns("U:U").Hidden = True
merged_cell = copied_worksheet.Range("A1:Z1")
merged_cell.Merge()
copied_worksheet.Cells(1, 1).Value = testi_intestazioni[i]
copied_worksheet.Cells(1, 1).Font.Name = "Arial"
copied_worksheet.Cells(1, 1).Font.Size = 35
copied_worksheet.Cells(1, 1).Font.Bold = True
copied_worksheet.Cells(1, 1).Font.Color = 255 # RGB for Blue
# Configurazione della stampa
copied_worksheet.PageSetup.Orientation = xlLandscape
copied_worksheet.PageSetup.PaperSize = xlPaperA4
copied_worksheet.PageSetup.FitToPagesWide = 1
copied_worksheet.PageSetup.FitToPagesTall = False
copied_worksheet.PrintOut()
workbook.Sheets(2).Delete()
files_printed += 1 # Incrementa il contatore di file stampati
workbook.Close(False)
excel.Quit()
if files_printed == 0:
messagebox.showwarning("Attenzione", "Nessun file disponibile per i filtri selezionati.")
else:
messagebox.showinfo("Successo", "Stampa completata con successo.")
except Exception as e:
excel.Quit()
messagebox.showerror("Errore", f"Si è verificato un errore: {e}")
def start_gui():
def start_printing():
choice = print_option.get()
week = week_entry.get().strip()
day = day_entry.get() # Ottieni il valore dal Combobox
if choice == 1:
printmanager(source_folder)
elif choice == 2:
printmanager(source_folder, week_filter=week if week else None)
elif choice == 3:
printmanager(source_folder, week_filter=week if week else None, day_filter=day if day else None)
root = tk.Tk()
root.title("DMS - Doors Print Manager")
root.geometry("600x300")
print_option = IntVar(value=1)
Radiobutton(root, text="Stampa tutti i file", variable=print_option, value=1, font=("Helvetica", 12), fg="blue").pack(anchor='c')
Radiobutton(root, text="Stampa file per settimana", variable=print_option, value=2, font=("Helvetica", 12), fg="magenta").pack(anchor='c')
Radiobutton(root, text="Stampa file per giorno specifico", variable=print_option, value=3, font=("Helvetica", 12), fg="black").pack(anchor='c')
separator = ttk.Separator(root, orient='horizontal')
separator.pack(fill='x', padx=10, pady=10)
Label(root, text="Inserisci settimana (WW):", font=("Helvetica", 12)).pack()
week_entry = Entry(root)
week_entry.pack()
# Opzioni per il giorno
Label(root, text="Seleziona giorno:").pack()
# Elenco dei giorni della settimana
days = ['LU', 'MA', 'ME', 'GI', 'VE']
day_entry = ttk.Combobox(root, values=days, state="readonly")
day_entry.pack()
day_entry.set('Seleziona un giorno') # Testo predefinito
Button(root, text="Inizia Stampa", command=start_printing, font=("Helvetica", 12, "bold"), fg="green").pack(pady=10)
root.mainloop()
if __name__ == "__main__":
# Imposta il percorso della cartella sorgente dei file Excel
source_folder = r"\path"
start_gui()
</code>
<code>import os import re import win32com.client # type: ignore import tkinter as tk from tkinter import messagebox, Radiobutton, Entry, Label, Button, IntVar, ttk # Costanti per gli stili di bordo di Excel e il formato di carta xlEdgeBottom = 9 xlContinuous = 1 xlPaperA4 = 9 # Formato carta A4 xlLandscape = 2 # Orientamento orizzontale # Testi per le intestazioni delle 4 copie di stampa testi_intestazioni = [ "Text 1", "Text 2", "Text 3", "Text 4" ] def get_sort_key(filename): days = {'LU': 1, 'MA': 2, 'ME': 3, 'GI': 4, 'VE': 5} # Mappa i giorni a valori numerici parts = filename.split('_') week = int(parts[-2]) day = days.get(parts[-1].split('.')[0], 0) return (week, day) def printmanager(cartella, week_filter=None, day_filter=None): excel = win32com.client.Dispatch("Excel.Application") excel.Visible = False # Imposta Excel non visibile durante l'esecuzione try: files_to_print = [f for f in os.listdir(cartella) if f.endswith(('.xls', '.xlsx'))] files_to_print.sort(key=get_sort_key) files_printed = 0 # Contatore per tracciare il numero di file stampati for filename in files_to_print: # Creazione di un pattern di ricerca per la settimana che isola esattamente il numero inserito if week_filter: week_pattern = fr'WK_{week_filter}_' # Assicura che il pattern includa W seguito dalla settimana e underscore if not re.search(week_pattern, filename): continue if day_filter: # Assumi che i giorni siano indicati nel filename con _LU, _MA, ecc. day_pattern = f'_{day_filter}' if day_pattern not in filename: continue full_path = os.path.join(cartella, filename) workbook = excel.Workbooks.Open(full_path) for i in range(4): workbook.Sheets(1).Copy(After=workbook.Sheets(1)) copied_worksheet = workbook.Sheets(2) copied_worksheet.Rows("1:1").Insert() copied_worksheet.Columns("Z:Z").Hidden = True copied_worksheet.Columns("U:U").Hidden = True merged_cell = copied_worksheet.Range("A1:Z1") merged_cell.Merge() copied_worksheet.Cells(1, 1).Value = testi_intestazioni[i] copied_worksheet.Cells(1, 1).Font.Name = "Arial" copied_worksheet.Cells(1, 1).Font.Size = 35 copied_worksheet.Cells(1, 1).Font.Bold = True copied_worksheet.Cells(1, 1).Font.Color = 255 # RGB for Blue # Configurazione della stampa copied_worksheet.PageSetup.Orientation = xlLandscape copied_worksheet.PageSetup.PaperSize = xlPaperA4 copied_worksheet.PageSetup.FitToPagesWide = 1 copied_worksheet.PageSetup.FitToPagesTall = False copied_worksheet.PrintOut() workbook.Sheets(2).Delete() files_printed += 1 # Incrementa il contatore di file stampati workbook.Close(False) excel.Quit() if files_printed == 0: messagebox.showwarning("Attenzione", "Nessun file disponibile per i filtri selezionati.") else: messagebox.showinfo("Successo", "Stampa completata con successo.") except Exception as e: excel.Quit() messagebox.showerror("Errore", f"Si è verificato un errore: {e}") def start_gui(): def start_printing(): choice = print_option.get() week = week_entry.get().strip() day = day_entry.get() # Ottieni il valore dal Combobox if choice == 1: printmanager(source_folder) elif choice == 2: printmanager(source_folder, week_filter=week if week else None) elif choice == 3: printmanager(source_folder, week_filter=week if week else None, day_filter=day if day else None) root = tk.Tk() root.title("DMS - Doors Print Manager") root.geometry("600x300") print_option = IntVar(value=1) Radiobutton(root, text="Stampa tutti i file", variable=print_option, value=1, font=("Helvetica", 12), fg="blue").pack(anchor='c') Radiobutton(root, text="Stampa file per settimana", variable=print_option, value=2, font=("Helvetica", 12), fg="magenta").pack(anchor='c') Radiobutton(root, text="Stampa file per giorno specifico", variable=print_option, value=3, font=("Helvetica", 12), fg="black").pack(anchor='c') separator = ttk.Separator(root, orient='horizontal') separator.pack(fill='x', padx=10, pady=10) Label(root, text="Inserisci settimana (WW):", font=("Helvetica", 12)).pack() week_entry = Entry(root) week_entry.pack() # Opzioni per il giorno Label(root, text="Seleziona giorno:").pack() # Elenco dei giorni della settimana days = ['LU', 'MA', 'ME', 'GI', 'VE'] day_entry = ttk.Combobox(root, values=days, state="readonly") day_entry.pack() day_entry.set('Seleziona un giorno') # Testo predefinito Button(root, text="Inizia Stampa", command=start_printing, font=("Helvetica", 12, "bold"), fg="green").pack(pady=10) root.mainloop() if __name__ == "__main__": # Imposta il percorso della cartella sorgente dei file Excel source_folder = r"\path" start_gui() </code>
import os
import re
import win32com.client # type: ignore
import tkinter as tk
from tkinter import messagebox, Radiobutton, Entry, Label, Button, IntVar, ttk

# Costanti per gli stili di bordo di Excel e il formato di carta
xlEdgeBottom = 9
xlContinuous = 1
xlPaperA4 = 9  # Formato carta A4
xlLandscape = 2  # Orientamento orizzontale

# Testi per le intestazioni delle 4 copie di stampa
testi_intestazioni = [
    "Text 1",
    "Text 2",
    "Text 3",
    "Text 4"
]

def get_sort_key(filename):
    days = {'LU': 1, 'MA': 2, 'ME': 3, 'GI': 4, 'VE': 5}  # Mappa i giorni a valori numerici
    parts = filename.split('_')
    week = int(parts[-2])
    day = days.get(parts[-1].split('.')[0], 0)
    return (week, day)

def printmanager(cartella, week_filter=None, day_filter=None):
    excel = win32com.client.Dispatch("Excel.Application")
    excel.Visible = False  # Imposta Excel non visibile durante l'esecuzione

    try:
        files_to_print = [f for f in os.listdir(cartella) if f.endswith(('.xls', '.xlsx'))]
        files_to_print.sort(key=get_sort_key)

        files_printed = 0  # Contatore per tracciare il numero di file stampati

        for filename in files_to_print:
            # Creazione di un pattern di ricerca per la settimana che isola esattamente il numero inserito
            if week_filter:
                week_pattern = fr'WK_{week_filter}_'  # Assicura che il pattern includa W seguito dalla settimana e underscore
                if not re.search(week_pattern, filename):
                    continue
            
            if day_filter:
                # Assumi che i giorni siano indicati nel filename con _LU, _MA, ecc.
                day_pattern = f'_{day_filter}'
                if day_pattern not in filename:
                    continue
            
            full_path = os.path.join(cartella, filename)
            workbook = excel.Workbooks.Open(full_path)

            for i in range(4):
                workbook.Sheets(1).Copy(After=workbook.Sheets(1))
                copied_worksheet = workbook.Sheets(2)
                copied_worksheet.Rows("1:1").Insert()
                copied_worksheet.Columns("Z:Z").Hidden = True
                copied_worksheet.Columns("U:U").Hidden = True
                merged_cell = copied_worksheet.Range("A1:Z1")
                merged_cell.Merge()
                copied_worksheet.Cells(1, 1).Value = testi_intestazioni[i]
                copied_worksheet.Cells(1, 1).Font.Name = "Arial"
                copied_worksheet.Cells(1, 1).Font.Size = 35
                copied_worksheet.Cells(1, 1).Font.Bold = True
                copied_worksheet.Cells(1, 1).Font.Color = 255  # RGB for Blue

                # Configurazione della stampa
                copied_worksheet.PageSetup.Orientation = xlLandscape
                copied_worksheet.PageSetup.PaperSize = xlPaperA4
                copied_worksheet.PageSetup.FitToPagesWide = 1
                copied_worksheet.PageSetup.FitToPagesTall = False

                copied_worksheet.PrintOut()
                workbook.Sheets(2).Delete()

                files_printed += 1  # Incrementa il contatore di file stampati

            workbook.Close(False)

        excel.Quit()
        if files_printed == 0:
            messagebox.showwarning("Attenzione", "Nessun file disponibile per i filtri selezionati.")
        else:
            messagebox.showinfo("Successo", "Stampa completata con successo.")
    except Exception as e:
        excel.Quit()
        messagebox.showerror("Errore", f"Si è verificato un errore: {e}")

def start_gui():
    def start_printing():
        choice = print_option.get()
        week = week_entry.get().strip()
        day = day_entry.get()  # Ottieni il valore dal Combobox
        if choice == 1:
            printmanager(source_folder)
        elif choice == 2:
            printmanager(source_folder, week_filter=week if week else None)
        elif choice == 3:
            printmanager(source_folder, week_filter=week if week else None, day_filter=day if day else None)


    root = tk.Tk()
    root.title("DMS - Doors Print Manager")
    root.geometry("600x300")

    print_option = IntVar(value=1)
    Radiobutton(root, text="Stampa tutti i file", variable=print_option, value=1, font=("Helvetica", 12), fg="blue").pack(anchor='c')
    Radiobutton(root, text="Stampa file per settimana", variable=print_option, value=2, font=("Helvetica", 12), fg="magenta").pack(anchor='c')
    Radiobutton(root, text="Stampa file per giorno specifico", variable=print_option, value=3, font=("Helvetica", 12), fg="black").pack(anchor='c')

    separator = ttk.Separator(root, orient='horizontal')
    separator.pack(fill='x', padx=10, pady=10)

    Label(root, text="Inserisci settimana (WW):", font=("Helvetica", 12)).pack()
    week_entry = Entry(root)
    week_entry.pack()

    # Opzioni per il giorno
    Label(root, text="Seleziona giorno:").pack()
    # Elenco dei giorni della settimana
    days = ['LU', 'MA', 'ME', 'GI', 'VE']
    day_entry = ttk.Combobox(root, values=days, state="readonly")
    day_entry.pack()
    day_entry.set('Seleziona un giorno')  # Testo predefinito

    Button(root, text="Inizia Stampa", command=start_printing, font=("Helvetica", 12, "bold"), fg="green").pack(pady=10)

    root.mainloop()

if __name__ == "__main__":
    # Imposta il percorso della cartella sorgente dei file Excel
    source_folder = r"\path"
    start_gui()

I tried multiple ways to try to close excel in other ways, always work in win 11 but none in win 10.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật