【发布时间】:2018-09-05 17:01:22
【问题描述】:
我有一个巨大的 Excel 工作簿,里面有很多个人数据。每个人都有一个唯一的数字标识符,但有多行信息。
我想通过该标识符过滤所有内容,然后将结果行复制到模板 excel 工作簿并保存结果。我正在尝试使用 Python 和 openpyxl 来做到这一点。
我认为应用自动过滤器然后复制结果可以解决问题。但是好像openpyxl只能应用AutoFilter和not do the actual filtering?
我尝试关注this question 的答案,但它不会做任何事情。我想过滤 D 列 (4) 中的数字。
import openpyxl, os
from openpyxl.utils import range_boundaries
#Intitializes workbooks
print('Opening data file...')
min_col, min_row, max_col, max_row = range_boundaries("A:AG")
wb = openpyxl.load_workbook('Data.xlsx')
ws = wb.active
template = openpyxl.load_workbook('Template.xlsx')
templatews = template.active
#Asks for numeric identifier
print('Done! Now introduce identifier:')
filterNumber = input()
#Does the actual thing
for row in ws.iter_rows():
if row[3].value == str(filterNumber):
templatews.append((cell.value for cell in row[min_col-1:max_col]))
#Saves the results
template.save('templatesave.xlsx')
print('All done! Have fun!')
对此的任何见解将不胜感激。谢谢!
编辑:根据@alexis 的建议更正了列号,尽管它没有解决问题。
已解决:事实证明 IF 语句要求一个整数,而不是一个字符串。使用 int() 解决了这个问题。
for row in ws.iter_rows():
if row[3].value == int(filterNumber):
templatews.append((cell.value for cell in row[min_col-1:max_col]))
【问题讨论】:
标签: python excel filtering openpyxl autofilter