繁体   English   中英

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

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

我有一个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中打开,以便可以向用户显示正确的错误,并且程序停止崩溃?

您可以尝试以下方法:

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)

这是我用于相同问题的解决方案。 这是基于以下事实:至少在Windows中将文件锁定后,Excel才会放置一个临时文件。 我检查临时文件是否存在,并向用户显示一条消息以关闭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...")

暂无
暂无

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

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