我有一个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}")

推荐答案

在您的代码中,您同时使用win32comopenpyxl,这是不推荐的.try 使用一个库.

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()

Python相关问答推荐

大Pandas 胚胎中产生组合

pandas DataFrame GroupBy.diff函数的意外输出

根据二元组列表在pandas中创建新列

我想一列Panadas的Rashrame,这是一个URL,我保存为CSV,可以直接点击

导入...从...混乱

如何指定列数据类型

解决调用嵌入式函数的XSLT中表达式的语法移位/归约冲突

如何在Python中使用Pandas将R s Tukey s HSD表转换为相关矩阵''

将标签移动到matplotlib饼图中楔形块的开始处

Python—转换日期:价目表到新行

为什么t sns.barplot图例不显示所有值?'

使用Python TCP套接字发送整数并使用C#接收—接收正确数据时出错

python的文件. truncate()意外地没有截断'

如何使用大量常量优化代码?

来自Airflow Connection的额外参数

Pandas数据框上的滚动平均值,其中平均值的中心基于另一数据框的时间

极点用特定值替换前n行

Pandas ,快速从词典栏中提取信息到新栏

将鼠标悬停在海运`pairplot`的批注/高亮显示上

在Django REST框架中定义的URL获得404分