Openpyxl:如何检查单元格是否包含特定值后如何复制行 [英] Openpyxl: How to copy a row after checking if a cell contains specific value
问题描述
我有一个工作表,每周更新数千行,并且需要在过滤后从该工作表中转移行.我正在使用当前代码查找具有所需值的单元格,然后将整行传输到另一张工作表,但是保存文件后,出现"IndexError:列表索引超出范围"异常.
I have a worksheet that is updated every week with thousands of rows and would need to transfer rows from this worksheet after filtering. I am using the current code to find the cells which has the value I need and then transfer the entire row to another sheet but after saving the file, I get the "IndexError: list index out of range" exception.
我使用的代码如下:
import openpyxl
wb1 = openpyxl.load_workbook('file1.xlsx')
wb2 = openpyxl.load_workbook('file2.xlsx')
ws1 = wb1.active
ws2 = wb2.active
for row in ws1.iter_rows():
for cell in row:
if cell.value == 'TrueValue':
n = 'A' + str(cell.row) + ':' + ('GH' + str(cell.row))
for row2 in ws1.iter_rows(n):
ws2.append(row2)
wb2.save("file2.xlsx")
我以前用来工作的原始代码如下,由于大文件导致MS Excel无法打开它们(超过40mb),因此必须对其进行修改.
The original code I used that used to work is below and has to be modified because of the large files which causes MS Excel not to open them (over 40mb).
n = 'A3' + ':' + ('GH'+ str(ws1.max_row))
for row in ws1.iter_rows(n):
ws2.append(row)
谢谢.
推荐答案
使用列表保存特定行的每一列中的项目. 然后将该列表附加到您的 ws2 .
Use a list to hold the items in each column for the particular row. Then append the list to your ws2.
...
def iter_rows(ws,n): #produce the list of items in the particular row
for row in ws.iter_rows(n):
yield [cell.value for cell in row]
for row in ws1.iter_rows():
for cell in row:
if cell.value == 'TrueValue':
n = 'A' + str(cell.row) + ':' + ('GH' + str(cell.row))
list_to_append = list(iter_rows(ws1,n))
for items in list_to_append:
ws2.append(items)
这篇关于Openpyxl:如何检查单元格是否包含特定值后如何复制行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!