使用Python的openpyxl模块写数据到Excel当中,为什么有时候会无法关闭Excel文件

问题遇到的现象和发生背景

使用Python写Excel,有时候无法正常关闭Excel,导致下次再写入时,报Permission Error

问题相关代码,请勿粘贴截图
 import pandas as pd

        df = pd.DataFrame(results,
                          columns=['业务线', '部门', '组', '订单分类', '当月人数', 'GMV'])

        df.set_index("业务线", inplace=True)

        # df

        # 暂存到新表中

        df.to_excel("D:/report/temp_明细/暂存表.xlsx")

        # 更新数据源

        from openpyxl import load_workbook

        shuju_wb = load_workbook('D:/report/temp_明细/暂存表.xlsx')

        moban_wb = load_workbook('D:/report/报表模板/模板.xlsx')

        shuju_sheet = shuju_wb['Sheet1']

        moban_sheet = moban_wb['明细']

        #实现覆盖写,需要以数据行数多的数据集为标准
        if shuju_sheet.max_row >= moban_sheet.max_row:

            max_row = shuju_sheet.max_row

        else:

            max_row = moban_sheet.max_row

        for i in range(1, max_row + 1):

            for j in range(1, shuju_sheet.max_column + 1):
                moban_sheet.cell(row=i, column=j).value = shuju_sheet.cell(row=i, column=j).value

        print('已经正常写入数据')

        moban_wb.save('D:/report/报表模板/模板.xlsx')
运行结果及报错内容
D:\ProgramFile\anaconda\python.exe D:/NormalFiles/pythonProject/condaProject/测试代码/test1.py
该文件已被打开,需要先关闭
D:\ProgramFile\anaconda\lib\site-packages\openpyxl\worksheet\_reader.py:312: UserWarning: Unknown extension is not supported and will be removed
  warn(msg)
D:\ProgramFile\anaconda\lib\site-packages\openpyxl\worksheet\_reader.py:312: UserWarning: Conditional Formatting extension is not supported and will be removed
  warn(msg)
Traceback (most recent call last):
  File "D:/NormalFiles/pythonProject/condaProject/测试代码/test1.py", line 14, in <module>
    check_file_is_open()
  File "D:/NormalFiles/pythonProject/condaProject/测试代码/test1.py", line 11, in check_file_is_open
    opened_workbook.save('D:\\report\\报表模板\\模板.xlsx')
  File "D:\ProgramFile\anaconda\lib\site-packages\openpyxl\workbook\workbook.py", line 407, in save
    save_workbook(self, filename)
  File "D:\ProgramFile\anaconda\lib\site-packages\openpyxl\writer\excel.py", line 291, in save_workbook
    archive = ZipFile(filename, 'w', ZIP_DEFLATED, allowZip64=True)
  File "D:\ProgramFile\anaconda\lib\zipfile.py", line 1251, in __init__
    self.fp = io.open(file, filemode)
PermissionError: [Errno 13] Permission denied: 'D:\\report\\报表模板\\模板.xlsx'

我的解答思路和尝试过的方法

查资料没有查到相关的内容显示如何解决这个问题。

后面想着是不是可以预先判断一下Excel文件是否是打开。Excel文件在打开的状态下,会生成一个前缀为 '~$' 的文件,判断这个文件是否存在就可以判断该Excel文件是否处于打开状态:

def check_file_is_open():
    file_path='D:\\report\\报表模板'
    file_name='扩科业绩-模板.xlsx'
    temp_file=file_path+'\\'+'~$'+file_name
    if os.path.exists(temp_file):
        print('该文件已被打开,需要先关闭')
我想要达到的结果

希望有遇到过这个问题的同学帮我解答一下,这个问题产生的原因是什么,或者如何通过Python关闭在操作系统(Win11)当中手动打开的Excel文件,感谢!

手动关闭打开的文件,在用openpyxl写入后关闭f.close(),有的可能需要在资源管理器关闭进程。

你电脑是不是正在打开这个xlsx文件呀?

原因就是你用python打开了已经打开的excel文件。我建议你try except抛出异常,再通过os语句关闭它