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

标签 python excel save user-input openpyxl

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

最佳答案

这是我针对同一问题使用的解决方案。这是基于这样的事实:至少当文件在 Windows 中被锁定时,Excel 才会放置一个临时文件。我检查临时文件是否存在,并向用户提供关闭 Excel 文件的消息。理想情况下,给他们一个 GUI 窗口,其中包含 OK |取消会更好,但这是一个有效的开始。

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

关于Python 2.7 : Check if excel file is already open in program before saving it,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56057526/

相关文章:

Python:轻松打印变量名和值

Excel VBA : How to clear contents for specified cells when another cell contains specific text or string

android - 如何在 Remix OS 的终端仿真器中保存和退出 Vi

python - 使用 tf.train.MonitoredTrainingSession 时如何获取全局步骤

java - Android:将 arrayList 保存到文件不起作用

python - 使用python使用hadoop处理xml文件

Python文件操作

python - 我如何将 SMOTE 应用于多类文本数据

java - org.apache.poi.openxml4j.exceptions.InvalidOperationException : Can't open the specified file:

vba - 将宏作为加载项分发给其他用户