嗨,我刚开始学习python/编程,有以下问题:
我想用python刷新几个excel文件。然而,所有这些excel文件都有一个完全不同的文件路径,因此它们并不都存储在一个文件夹中。
使用pypiwin32
编写刷新一个excel文件的代码是没有问题的。为了用不同的文件路径刷新几个excel文件,目前我用以下方式解决了这个问题:
import win32com.client as win32
Xlsx = win32.DispatchEx('Excel.Application')
Xlsx.DisplayAlerts = False
Xlsx.Visible = False
book1 = Xlsx.Workbooks.Open('<path_to_excel_workbook1>')
book2 = Xlsx.Workbooks.Open('<path_to_excel_workbook2>')
book1.RefreshAll()
book2.RefreshAll()
Xlsx.CalculateUntilAsyncQueriesDone()
book1.Save()
book2.Save()
book1.Close(SaveChanges=True)
book2.Close(SaveChanges=True)
Xlsx.Quit()
del book1
del book2
del Xlsx
但是,当需要更新50个或更多Excel文件时,整个代码会变得不必要的长。有没有一种方法可以迭代所有的Excel文件,而不需要为每个Excel文件编写一行代码来执行RefreshAll()
、Save()
和Close()
?也许通过使用循环或相似的解决方案?
发布于 2022-07-18 12:57:03
我会做这样的事。
import win32com.client as win32
file_paths = ['path_one', 'path_two']
Xlsx = win32.DispatchEx('Excel.Application')
Xlsx.DisplayAlerts = False
Xlsx.Visible = False
for path in file_paths:
book = Xlsx.Workbooks.Open(path)
book.RefreshAll()
Xlsx.CalculateUntilAsyncQueriesDone()
book.Close(SaveChanges=True)
Xlsx.Quit()
发布于 2022-07-18 12:54:59
您希望创建一个可重用的函数,该函数接受filepath和Xlsx对象。然后,您可以对列表中的所有路径进行简单的循环。
def refresh_excel(Xlsx, filepath):
#everything under this indented code block is run every time you call refresh_excel
workbook = Xlsx.Workbooks.Open(filepath)
workbook.RefreshAll()
workbook.CalculateUntilAsyncQueriesDone()
workbook.Save()
workbook.Close() #this might not be needed
return True
#this unindented block sets up you Excel application and stores your list of excel filepaths you want to refresh
Xlsx = win32.DispatchEx('Excel.Application')
Xlsx.DisplayAlerts = False
Xlsx.Visible = False
file_list = ['path1.xlsx', 'path2.xlsx', 'path3.xlsx']
#create a loop that runs refresh_excel function, using every filename in your list.
#The Xlsx parameter ensures that you use the same Excel application,
#which would help speed up your script by not needlessly opening and
#closing a new Excel application for every file.
for file in file_list:
refresh_excel(Xlsx, file)
Xlsx.Quit()
用def
关键字表示,创建函数的唯一真正好处是,如果脚本增长,变得更加复杂,并且做更多的事情,它有助于保持事情的有序性,而不必尝试调试100行代码。
https://stackoverflow.com/questions/73022445
复制相似问题