簡體   English   中英

Openpyxl:如何檢查單元格是否包含特定值后如何復制行

[英]Openpyxl: How to copy a row after checking if a cell contains specific value

我有一個每周更新數千行的工作表,並且需要在過濾后從該工作表中轉移行。 我正在使用當前代碼查找具有所需值的單元格,然后將整行傳輸到另一張工作表,但是保存文件后,出現“ IndexError:列表索引超出范圍”異常。

我使用的代碼如下:

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)

謝謝。

我不確定您要做什么,但我懷疑問題是您嵌套了復制循環。

請嘗試以下操作:

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

使用列表來保存特定行的每一列中的項目。 然后將該列表附加到您的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)

問題 :我收到“ IndexError:列表索引超出范圍”異常。


我從ws1.iter_rows(n)

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

並來自ws2.append(row2)

 ValueError: Cells cannot be copied from other worksheets 

原因是row2確實list of Cell objects list of Values而不是list of Values


問題 :...需要在過濾后從此工作表傳輸行

例如,以下操作可以滿足您的要求:

# 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

我能夠通過我的項目清單解決此問題。

import openpyxl
#load data file
wb1 = openpyxl.load_workbook('original.xlsx')
sheet1 = wb1.active
print("loaded 1st file")    
#new template file
wb2 = openpyxl.load_workbook('blank.xlsx') 
sheet2 = wb2.active
print("loaded 2nd file")
header = sheet1[1:1] #grab header row
listH =[]
for h in header:
    listH.append(h.value)
sheet2.append(listH)
colOfInterest= 11 # this is my col that contains the value I'm checking against
for rowNum in range(2, sheet1.max_row +1):  #iterate over each row, starting with 2 to skipping header from original file
    if sheet1.cell(row=rowNum, column=colOfInterest).value is not None: #interested in non blank values in column 11
        listA = [] # list which will hold my data
        row = sheet1[rowNum:rowNum] #creates a tuple of row's data
        #print (str(rowNum))  # for debugging to show what rows are copied
        for cell in row:  # for each cell in the row
            listA.append(cell.value) # add each cell's data as an element in the list
        if listA[10]  == 1:  # condition1 I'm checking for by looking up the index in the list
            sheet2.append(listA)  # appending the sheet2's next available row
        elif listA[10] > 1:  # condition2 I'm checking for by looking up the index in the list
            # do something else and store it in bar
            sheet2.append(bar) # appending the sheet2's next available row

print("saving file...")
wb2.save('result.xlsx')  # save file
print("Done!")

經過測試:Python 3.7 openpyxl 2.5.4

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM