Python保存Excel更改时出现问题
我有一个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}")
1 个回答
2
在你的代码中,你同时使用了 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()