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?
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.