简体   繁体   English

Python 2.7:保存之前,请先检查程序中是否已打开excel文件

[英]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. 我有一个python程序,最后将excel报告保存在文件夹中。

I am using openpyxl and This is the part of the script which saves the excel file : 我正在使用openpyxl,这是保存excel文件的脚本的一部分:

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. 这里的问题是,如果用户已经在Microsoft Excel中打开reportFinal.xlsx,然后用户运行该程序以将相同的excel保存在同一文件夹中,则我的程序崩溃。

The obvious reason is that old reportFinal.xlsx cannot be replaced by new reportFinal.xlsx if it is already opened in Microsoft Excel. 明显的原因是,如果旧的reportFinal.xlsx已在Microsoft Excel中打开,则无法将其替换为新的reportFinal.xlsx。

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? 有没有办法检查脚本,如果Excel已在Microsoft Excel中打开,以便可以向用户显示正确的错误,并且程序停止崩溃?

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. 这是基于以下事实:至少在Windows中将文件锁定后,Excel才会放置一个临时文件。 I check for the presence of the temp file, and give the user a message to close the Excel file. 我检查临时文件是否存在,并向用户显示一条消息以关闭Excel文件。 Ideally, giving them a GUI window with OK | 理想情况下,给他们提供具有OK的GUI窗口。 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...")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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