如何使用Openpyxl筛选列数据

How to filter column data using openpyxl(如何使用Openpyxl筛选列数据)
本文介绍了如何使用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")

这篇关于如何使用Openpyxl筛选列数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Leetcode 234: Palindrome LinkedList(Leetcode 234:回文链接列表)
How do I read an Excel file directly from Dropbox#39;s API using pandas.read_excel()?(如何使用PANDAS.READ_EXCEL()直接从Dropbox的API读取Excel文件?)
subprocess.Popen tries to write to nonexistent pipe(子进程。打开尝试写入不存在的管道)
I want to realize Popen-code from Windows to Linux:(我想实现从Windows到Linux的POpen-code:)
Reading stdout from a subprocess in real time(实时读取子进程中的标准输出)
How to call type safely on a random file in Python?(如何在Python中安全地调用随机文件上的类型?)