我有一个Python程序,需要执行以下操作:打开一个excel文件,将其另存为新副本,然后在新副本中写入一些内容,然后保存。程序运行。根据控制台输出,该单词已添加到单元格中,但当我打开它时,却看不到它。
我知道 Microsoft 并未正式支持自动化 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}")
在您的代码中,您同时使用
win32com
和 openpyxl
,不建议这样做。尝试使用一个库。
wb = excel.Workbooks.Open(file_path)
ws = openpyxl.load_workbook(file_path).active
sheet = excel.Workbooks.Open(file_path).Sheets('Messstellenplanung')
在上面的代码中,您在第一行中使用
win32com
打开文件。然后使用 openpyxl
打开相同的文件,而不是使用上面的代码
wb = openpyxl.load_workbook(file_path)
ws = wb['Messstellenplanung']
不要使用不必要的 for 循环,而是在进行更改后直接保存并关闭文件。
cell = ws['Q3']
cell.value = cell.value + 'Testing123'
wb.save()
wb.close()