【问题标题】:How can I copy Excel rows, filtering for a value, with Python and openpyxl?如何使用 Python 和 openpyxl 复制 Excel 行、过滤值?
【发布时间】: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


    【解决方案1】:

    iter_rows() 方法返回一个元组序列,因此它们从零开始索引:D 列位于索引 3。换句话说,试试这个方法:

    for row in ws.iter_rows():
        if row[3].value == str(filterNumber):
            ...
    

    如果它不起作用,让您的脚本打印一些列的值并从那里获取。也许这个单元格的格式不是你所期望的等等。

    【讨论】:

    • 谢谢!它没有解决它,尽管我确信这是问题的一部分。我认为它实际上并没有在新工作表中附加行。试图找出原因。
    • 我解决了!不过,感谢索引提示,这也是其中的一部分。
    【解决方案2】:

    我终于解决了! 原来,

    for row in ws.iter_rows():
        if row[1].value == int(filterNumber):
            templatews.append(cell.value for cell in row[min_col-1:max_col])
    

    在 IF 语句中要求一个整数而不是一个字符串。使用 int() 方法解决了这个问题。

    【讨论】:

      猜你喜欢
      • 2018-01-02
      • 1970-01-01
      • 2020-03-22
      • 2014-03-30
      • 2022-12-18
      • 2021-10-01
      • 2012-12-07
      • 1970-01-01
      • 2010-10-03
      相关资源
      最近更新 更多