python - 如何使用openpyxl过滤列数据

标签 python openpyxl

我正在尝试将筛选器应用于现有 Excel 文件,并将其导出到另一个 Excel 文件。我想提取仅包含值 16 的行,然后将表导出到另一个 Excel 文件(如下图所示)。

我已尝试多次阅读 openpyxl 文档并通过谷歌搜索解决方案,但我仍然无法使我的代码工作。我还附上了下面的代码和文件

import openpyxl
# Is use to create a reference of the Excel to wb
 wb1 = openpyxl.load_workbook('test_data.xlsx')
 wb2 = openpyxl.load_workbook('test_data_2.xlsx')

# Refrence the workbook to the worksheets
 sh1 = wb1["data_set_1"]
 sh2 = wb2["Sheet1"]

 sh1.auto_filter.ref = "A:A"
 sh1.auto_filter.add_filter_column(0, ["16"])
 sh1.auto_filter.add_sort_condition("B2:D6")

 sh1_row_number = sh1.max_row
 sh1_col_number = sh1.max_column

 rangeSelected = []
 for i in range(1, sh1_row_number+1, 1):
     rowSelected = []
     for j in range(1, sh1_col_number+1, 1):
         rowSelected.append(sh1.cell(row = i, column = j))
     rangeSelected.append(rowSelected)

  del rowSelected

 for i in range(1, sh1_row_number+1, 1):
    for j in range(1, sh1_col_number+1, 1):
        sh2.cell(row = i, column = j).value = rangeSelected[i-1][j-1].value

 wb1.save("test_data.xlsx")
 wb2.save("test_data_2.xlsx")

The pictures shows what should be the desire result

最佳答案

自动过滤器实际上并不过滤数据,它只是为了可视化。 您可能想在循环工作簿时进行过滤。请注意,对于此代码,我假设您在第二个工作簿中已有表标题。它不会覆盖数据,而是附加到表中。

import openpyxl
# Is use to create a reference of the Excel to wb
wb1 = openpyxl.load_workbook('test_data.xlsx')
wb2 = openpyxl.load_workbook('test_data_2.xlsx')

# Refrence the workbook to the worksheets
sh1 = wb1["data_set_1"]
sh2 = wb2["data_set_1"]   # use same sheet name, different workbook

for row in sh1.iter_rows():
    if row[0].value == 16:   # filter on first column with value 16
        sh2.append((cell.value for cell in row))     

wb1.save("test_data.xlsx")
wb2.save("test_data_2.xlsx")

关于python - 如何使用openpyxl过滤列数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51943487/

相关文章:

python - 我可以在 Python 中使用类而不是带有映射的函数吗?

python - PyTorch - 如何设置神经元的激活规则以提高神经网络的效率?

带有辅助 y 轴的 Python openpyxl 散点图

python - openpyxl 只读 use_iterators

python - 在openpyxl中查看行值

python - 查看 Python 中特定值周围的 +/- 范围的优雅方法

python - "^"在正则表达式模式中出错

python - Python 中的 % 语法

python - 使用 xlwt 与 openpyxl

python - numpy:屏蔽数组的 ndenumerate?