【问题标题】:Python 2.7 : Check if excel file is already open in program before saving itPython 2.7:在保存之前检查excel文件是否已经在程序中打开
【发布时间】:2019-09-27 04:16:30
【问题描述】:

我有一个 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 中打开,是否有任何方法可以签入脚本,以便向用户显示正确的错误并且程序停止崩溃?

【问题讨论】:

  • 你应该检查文件是否被锁定。

标签: python excel save user-input openpyxl


【解决方案1】:

你可以试试这个:

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)

【讨论】:

  • 如果您只允许代码捕获特定错误而不是仅捕获异常,这会更好。 (恐怕我不知道这会引发什么错误,WindowsPermissionError 什么的??)
【解决方案2】:

这是我用于相同问题的解决方案。它基于这样一个事实,即 Excel 至少会在文件被锁定在 Windows 中时放置一个临时文件。我检查临时文件是否存在,并给用户一条关闭 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...")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多