我有一个python程序,最后将excel报告保存在文件夹中。
我正在使用openpyxl,这是保存excel文件的脚本的一部分:
excelFilePath = reportsPath + "/reportFinal.xlsx"
wb.save(excelFilePath)
这里的问题是,如果用户已经在Microsoft Excel中打开reportFinal.xlsx,然后用户运行该程序以将相同的excel保存在同一文件夹中,则我的程序崩溃。
明显的原因是,如果旧的reportFinal.xlsx已在Microsoft Excel中打开,则无法将其替换为新的reportFinal.xlsx。
是否有任何方法可以检查脚本,如果Excel已在Microsoft Excel中打开,以便可以向用户显示正确的错误并且程序停止崩溃?
答案 0 :(得分:0)
您可以尝试以下操作:
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)
答案 1 :(得分:0)
这是我用于相同问题的解决方案。这是基于以下事实:至少在Windows中将文件锁定后,Excel才会放置一个临时文件。我检查临时文件是否存在,并向用户显示一条消息以关闭Excel文件。理想情况下,给他们提供具有OK的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 Cancel\n"
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...")