解决openpyxl读取excel失败后,无法删除此excel的问题

一、介绍

在使用openpyxl读取已损坏的excel,此时你想删除此excel新建一个,但你会发现删除不掉,提示excel正在被另一个程序读取中。

原因是当你的主线程用openpyxl读取excel失败时,它没有释放此读取资源,办法是用一个子线程去测试读取,如果有错误就让主线程去删除文件

二、代码

import gc
import os
import threading, traceback, sys
from openpyxl import load_workbook, Workbook

class runScriptThread(threading.Thread):  # The timer class is derived from the class threading.Thread
    def __init__(self, funcName, *args):
        threading.Thread.__init__(self)
        self.args = args
        self.funcName = funcName
        self.exitcode = 0
        self.exception = None
        self.exc_traceback = ''

    def run(self):  # Overwrite run() method, put what you want the thread do here
        try:
            self._run()
        except Exception as e:
            self.exitcode = 1  # 如果线程异常退出,将该标志位设置为1,正常退出为0
            self.exception = e
            self.exc_traceback = ''.join(traceback.format_exception(*sys.exc_info()))  # 在改成员变量中记录异常信息

    def _run(self):
        try:
            self.funcName(*(self.args))
        except Exception as e:
            raise e

path=r"****************.xlsx"

def read_openxl():
    wb = load_workbook(path,read_only=True)

aChildThread = runScriptThread(read_openxl)
aChildThread.start()
aChildThread.join()

if aChildThread.exitcode==1:
    del aChildThread
    gc.collect()
    os.remove(path)
    wb=Workbook()
    wb.save(path)

else:
    wb = load_workbook(path,read_only=True)
    sheet_list=wb.get_sheet_names()
    print(sheet_list)

 

上一篇:winform退出或关闭窗体时弹窗提示代码:转


下一篇:Java 插入、隐藏/显示、删除Excel行或列