我有一个Python程序,它需要做以下事情:打开一个EXCEL文件,另存为一个新的副本,然后在新的副本中写一些东西,然后保存.程序运行.根据控制台的输出,单词被添加到单元格中,但当我打开它时,哪里也看不到它.
我知道微软并没有正式支持Office自动化,但这是必须要做的.
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}")