解决openpyxl读取excel失败后,无法删除此excel的问题
Excel 解决 删除 无法 读取 失败 问题 openpyxl
2023-09-14 09:00:36 时间
一、介绍
在使用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)
相关文章
- MS SQLServer相关自动化程序的问题汇总 (SQLServer每天定时输出EXCEL或xml的格式的问题等 )
- Excel操作-用excel实现爬取网站上表格数据
- 解决方法:未能加载文件或程序集“Microsoft.Office.Interop.Excel。。
- Office EXCEL 如何将复制的一堆数据按空格断开
- Excel日常操作
- asp.net中导出excel数据的方法汇总
- EasyUI datagrid-export 将datagrid的数据导出至Excel-解决科学计数法
- 用Python的pandas框架操作Excel文件中的数据教程
- 如何用excel统计调查问卷
- 解决openpyxl读取excel失败后,无法删除此excel的问题
- 使用JavaScript把页面上的表格导出为Excel文件[转]
- 解决PHP生成UTF-8编码的CSV文件用Excel打开乱码的问题
- 使用Python处理Excel表格的简单方法
- 把数据库中的数据制作成Excel数据
- C# 获取Excel工作薄中Sheet页(工作表)名集合
- 如何使用 SAP Intelligent Robotic Process Automation 自动操作 Excel
- Atitit poi读取大文件内存溢出的解决 目录 1. poi提供了两种读取excel的方式,一种是类似xml的Dom,1 2. POI官网上提到XSSF有三种读写excel,POI地址1 3
- 成功解决在excel表格中仅在某列内插入一个空白单元格,使其下部的数据整体下移一格
- 成功解决在excel表中通过数学函数转换后,接着去掉公式转为不再随着变化的数值
- Qt毫秒级读取Excel文件
- 已解决xlrd.biffh.XLRDError: Excel xlsx file; not supported
- 已解决ImportError: Missing optional dependency ‘xlrd‘. Install xlrd >= 1.0.0 for Excel support Use pip
- 已解决Python pandas读取Excel表格某些数值字段结果为NaN问题
- 〖Python自动化办公篇⑫〗- Excel 文件自动化 - 读取 excel 数据
- Python办公自动化|10个方法,是时候对Excel下手了
- 使用excel进行数据挖掘(6)---- 预測
- GridView导出Excel的超好样例
- excel VLOOKUP 函数 在表格或区域中按行查找内容 函数 将2个表中有相同数据的一列,自动填写
- 玩转excel===Excel处理txt文件中的数据,Excel中的分列处理
- JAVA操作Excel表格:方法二:POI的使用①:Excel实战之POI创建excel文件(低版本)
- Excel 2016 突然打开别人发过来的2个excel文件就关闭打不开,打开电脑上其他excel文件正常