python2.7:在保存i之前,检查excel文件是否已经在程序中打开

2024-10-03 15:26:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个python程序,它最终将excel报表保存在一个文件夹中。在

我正在使用openpyxl,这是保存excel文件的脚本部分:

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

问题是如果报表最终.xlsx已由用户在Microsoft Excel中打开,然后用户运行程序将同一Excel保存在同一文件夹中,则我的程序将崩溃。在

很明显的原因是报表最终.xlsx无法替换为新的报表最终.xlsx如果它已经在Microsoft Excel中打开。在

如果excel已经在microsoftexcel中打开了,有什么方法可以签入脚本,这样用户就可以看到一个正确的错误,程序就不会崩溃了?在


Tags: 文件用户程序脚本文件夹报表xlsxexcel
2条回答

这是我用来解决同样问题的方法。它是基于这样一个事实:当文件至少在Windows中被锁定时,Excel会放置一个临时文件。我检查temp文件是否存在,并给用户一条关闭Excel文件的消息。理想情况下,给他们一个带有OK | Cancel的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...")

你可以试试这个:

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)

相关问题 更多 >