Python:在多个Excel表中搜索关键字,返回另一个单元格



我有一堆Excel模板,它们在单元格位置的设置不一致,也不是表格形式,但我希望将它们全部合并到一个表中。例如,一个Excel工作簿中的"项目"字段位于图纸1、A6中,而另一个工作簿中的图纸2、B5中。

我想做的是让python脚本在Excel文件中循环,并找到给定关键字的位置。从那里,将值N个单元格返回到右边(有些字段已经合并了单元格,因此它需要是右边的2个单元格(。有什么想法吗?

这可能不是完整的逻辑,但它会让你开始。它在工作簿中搜索带有"Report"的单元格,然后返回偏移量单元格的值。

import openpyxl
wb = openpyxl.load_workbook('test.xlsx')
shiftcol = 5 # offset from 'Report' cell
shiftrow = 5
found = False
for sn in wb.sheetnames:  # all sheets in workbook
if found: break
ws = wb.get_sheet_by_name(sn)
for cl in range(1,51):  # search 50 columns
if found: break
for rw in range(1,51):   # search 50 rows
if found: break
if ws.cell(rw,cl).value == 'Report':  # search for first cell with this value
print('Found Report. Sheet='+sn+' Col=' + str(cl) + ' Row=' + str(rw))
print("Value=" + str(ws.cell(rw+shiftrow, cl+shiftcol).value)) # offset to find target value
found = True 
if not found:
print ("Report field not found") # didn't find cell with 'Report'

最新更新