pythonexcelwin32com

Issue saving changes made in excel by python


I have a Python program which needs to do the following thing: Open an excel file, save it as a new copy, then in the new copy write something, then save. The program runs. According to the console output, the word gets added to the cell, but when I open it, it is nowhere to be seen.

I know that Microsoft doesn't officially support automating Office, but this needs to be done.

import win32com.client as win32
import tkinter as tk
import os
import openpyxl
from tkinter import messagebox
from openpyxl import load_workbook  
from datetime import datetime
from pywintypes import com_error
import time
import logging
import itertools

starter_row = 7

def get_time():
    now=datetime.now()
    current_time = now.strftime("%Y-%m-%d_%H-%M")
    return current_time    


try:
    excel=win32.gencache.GetActiveObject("Excel.Application")
except:
    excel=win32.gencache.EnsureDispatch("Excel.Application")
excel.Visible = True
old_file_path = excel.GetOpenFilename(FileFilter="Excel Files (*.xlsx; *.xlsm), *.xlsx; *.xlsm")
wb = excel.Workbooks.Open(old_file_path)
wb.RefreshAll()  ## Refresh external connection datas
excel.CalculateUntilAsyncQueriesDone()  ## Wait until the refresh has completed
file_name = os.path.basename(old_file_path)
directory_path = os.path.dirname(old_file_path).replace('\\', "/")
#We make a copy of the file with the current date and time, then open that one, so the original stays intact.
new_file_name = (file_name.rsplit('.', 1)[0]) + '_' + get_time() + '.xlsm'
file_path = directory_path + '/' + new_file_name
wb.SaveCopyAs (file_path)
excel.Quit()
excel.Visible = True
wb = excel.Workbooks.Open(file_path)
ws = openpyxl.load_workbook(file_path).active
sheet = excel.Workbooks.Open(file_path).Sheets('Messstellenplanung')

print("active worksheet: ", ws, " filepath: ", file_path)
print(ws['Q3'].value)
cell= ws['Q3']
cell.value = cell.value + "Testing123"
print(ws['Q3'].value)

for wb in excel.Workbooks:
    print("WB:",wb.Name)
    wb.Save()
wb.RefreshAll()
messagebox.showinfo(title="Success",message=f"The program ran succesfully. The new file's name is: {new_file_name}")

Solution

  • In your code you are using win32com and openpyxl together, which is not recommended. Try using one library.

    wb = excel.Workbooks.Open(file_path)
    ws = openpyxl.load_workbook(file_path).active
    sheet = excel.Workbooks.Open(file_path).Sheets('Messstellenplanung')
    

    In the above code, you are opening the file using win32com in the first line. Then opening the same file using openpyxl Instead of the above use the below code

    wb = openpyxl.load_workbook(file_path)
    ws = wb['Messstellenplanung']
    

    Instead of using for loop, which is unnecessary, directly save and close the file after making the changes.

    cell = ws['Q3']
    cell.value = cell.value + 'Testing123'
    wb.save()
    wb.close()