简体   繁体   中英

Python 2.7 : Check if excel file is already open in program before saving it

I have a python program which in the end saves an excel report in a folder.

I am using openpyxl and This is the part of the script which saves the excel file :

excelFilePath = reportsPath + "/reportFinal.xlsx"
wb.save(excelFilePath)

The problem here is if reportFinal.xlsx is already opened by the user in Microsoft Excel and then user runs the program to save same excel in same folder then my program crashes.

The obvious reason is that old reportFinal.xlsx cannot be replaced by new reportFinal.xlsx if it is already opened in Microsoft Excel.

Is there any way to check in script if the excel is already opened in Microsoft Excel so that a proper error can be shown the user and program stops crashing?

you can try this:

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)

Here is a solution I used for the same problem. It is based on the fact that Excel will place a temp file when the file is locked in Windows at least. I check for the presence of the temp file, and give the user a message to close the Excel file. Ideally, giving them a GUI window with OK | Cancel would be better, but this is a start that works.

#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...")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM