Openpyxl:检查单元格是否包含特定值后如何复制行

2024-05-15 15:06:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个每周更新数千行的工作表,筛选后需要从该工作表中转移行。我正在使用当前代码查找具有所需值的单元格,然后将整行传输到另一个工作表,但在保存文件后,出现“IndexError:list index out of range”异常。

我使用的代码如下:

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)。

n = 'A3' + ':' + ('GH'+ str(ws1.max_row))
for row in ws1.iter_rows(n):
    ws2.append(row)

谢谢。


Tags: 文件代码inforcellxlsxrowsrow
3条回答

Question: I get the "IndexError: list index out of range" exception.


I get, from ws1.iter_rows(n)

UserWarning: Using a range string is deprecated. Use ws[range_string]

and from ws2.append(row2).

ValueError: Cells cannot be copied from other worksheets

The Reason are row2 does hold a list of Cell objects instead of a list of Values


Question: ... need to transfer rows from this worksheet after filtering

例如,以下操作可以满足您的需要:

# If you want to Start at Row 2 to append Row Data
# Set Private self._current_row to 1
ws2.cell(row=1, column=1).value = ws2.cell(row=1, column=1).value

# Define min/max Column Range to copy
from openpyxl.utils import range_boundaries
min_col, min_row, max_col, max_row = range_boundaries('A:GH')

# Define Cell Index (0 Based) used to Check Value
check = 0 # == A

for row in ws1.iter_rows():
    if row[check].value == 'TrueValue':
        # Copy Row Values
        # We deal with Tuple Index 0 Based, so min_col must have to be -1
        ws2.append((cell.value for cell in row[min_col-1:max_col]))

使用Python测试:3.4.2-openpyxl:2.4.1-LibreOffice:4.3.3.2

使用列表保存特定行的每列中的项。 然后将列表附加到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)

我不完全确定您要做什么,但我怀疑问题是您嵌套了复制循环。

请尝试以下操作:

row_nr = 1
for row in ws1:
    for cell in row:
        if cell.value == "TrueValue":
            row_nr = cell.row
            break
    if row_nr > 1:
        break

for row in ws1.iter_rows(min_row=row_nr, max_col=190):
    ws2.append((cell.value for cell in row))

相关问题 更多 >