我有一个Python程序,该程序最终将Excel报告保存在文件夹中。
我正在使用openpyxl,这是脚本保存excel文件的一部分:
excelFilePath = reportsPath + "/reportFinal.xlsx"
wb.save(excelFilePath)
问题是,如果用户已经在Microsoft Excel中打开了ReportFinal.xlsx,然后用户运行该程序将同一Excel保存在同一文件夹中,然后我的程序崩溃。
显而易见的原因是,如果已经在Microsoft Excel中打开了旧的reportfinal.xlsx,则不能被新的reportfinal.xlsx替换。
是否有任何方法可以在Microsoft Excel中打开Excel,以便可以向用户显示正确的错误,并且程序停止崩溃?
这是我用于同一问题的解决方案。这是基于以下事实:Excel至少将文件锁定在Windows中时将放置一个临时文件。我检查是否存在临时文件,并给用户一条消息以关闭Excel文件。理想情况下,给他们一个GUI窗口,取消会更好,但这是一个有效的开始。
#Check to see if an Excel file is open by another program before attempting to open it.
import os.path
from os import path
excelFile = "yourExcelFileName.xlsx"
tempFileName = ( '~$' + excelFile ) #Define the temp file name Microsoft Excel uses.
fileCheck = path.isfile(tempFileName) #Returns a boolean as True if tempFileName exists.
maxAsks = 4 #Limit how many times we ask for user to close file before exiting.
i = 0 #Incrementing so we can limit the loop.
while ( i < maxAsks) and ( fileCheck == True ):
if ( fileCheck == True ): #If tempFileName exists,
choiceText = "---------------------nExcel file is open. Please close: " + excelFile + "nPress 1 to Continue | 0 to Canceln"
inputChoice = input(choiceText)
if inputChoice=="0":
exit("Cancelling")
elif inputChoice=="1":
#Check if tempFileName is gone now.
fileCheck = path.isfile(tempFileName)
else:
print("Invalid entry, exiting.n")
exit("Valid entries are 0 or 1, you chose: " + inputChoice + "n")
i += 1 #Increment i
#Script continues from here as normal...
print("Continuing script here...")
您可以尝试以下方法:
def not_in_use(filename):
try:
os.rename(filename,filename)
return True
except:
return False
excelFilePath = reportsPath + "/reportFinal.xlsx"
if not_in_use(excelFilePath):
wb.save(excelFilePath)