Python Openpyxl优化单元格搜索速度
我需要在Excel表格中搜索包含某些图案的单元格。这花的时间比我能应付的还多。下面是我能写的最优化的代码。因为数据模式通常是一行接一行的,所以我使用iter_行(row_offset=x)。不幸的是,下面的代码发现给定的模式在每个for循环中的次数越来越多(从毫秒开始,到几乎一分钟)。我做错了什么Python Openpyxl优化单元格搜索速度,python,excel,openpyxl,Python,Excel,Openpyxl,我需要在Excel表格中搜索包含某些图案的单元格。这花的时间比我能应付的还多。下面是我能写的最优化的代码。因为数据模式通常是一行接一行的,所以我使用iter_行(row_offset=x)。不幸的是,下面的代码发现给定的模式在每个for循环中的次数越来越多(从毫秒开始,到几乎一分钟)。我做错了什么 import openpyxl import datetime from openpyxl import Workbook wb = Workbook() ws = wb.active ws.tit
import openpyxl
import datetime
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
ws.title = "test_sheet"
print("Generating quite big excel file")
for i in range(1,10000):
for j in range(1,20):
ws.cell(row = i, column = j).value = "Cell[{},{}]".format(i,j)
print("Saving test excel file")
wb.save('test.xlsx')
def FindXlCell(search_str, last_r):
t = datetime.datetime.utcnow()
for row in ws.iter_rows(row_offset=last_r):
for cell in row:
if (search_str == cell.value):
print(search_str, last_r, cell.row, datetime.datetime.utcnow() - t)
last_r = cell.row
return last_r
print("record not found ",search_str, datetime.datetime.utcnow() - t)
return 1
wb = openpyxl.load_workbook("test.xlsx", data_only=True)
t = datetime.datetime.utcnow()
ws = wb["test_sheet"]
last_row = 1
print("Parsing excel file in a loop for 3 cells")
for i in range(1,100,1):
last_row = FindXlCell("Cell[0,0]", last_row)
last_row = FindXlCell("Cell[1000,6]", last_row)
last_row = FindXlCell("Cell[6000,6]", last_row)
在工作表上循环多次是低效的。搜索速度越来越慢的原因似乎是每个循环中使用的内存越来越多。这是因为
last_row=FindXlCell(“Cell[0,0]”,last_row)
意味着下一次搜索将在行的末尾创建新的单元格:openpyxl根据需要创建单元格,因为行在技术上可以为空,但其中的单元格仍然可以寻址。在脚本末尾,工作表总共有598000行,但您总是从A1
开始搜索
如果您希望在一个大文件中多次搜索文本,那么创建一个以坐标为值的文本键控矩阵可能是有意义的
比如:
matrix = {}
for row in ws:
for cell in row:
matrix[cell.value] = (cell.row, cell.col_idx)
在实际示例中,您可能希望使用defaultdict
来处理具有相同文本的多个单元格
这可以与只读模式结合使用,以减少内存占用。当然,如果要编辑文件,则除外