[英]Python 2.7 : Check if excel file is already open in program before saving it
我有一個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中打開,以便可以向用戶顯示正確的錯誤,並且程序停止崩潰?
您可以嘗試以下方法:
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)
這是我用於相同問題的解決方案。 這是基於以下事實:至少在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...")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.