簡體   English   中英

如果條件基於使用 Openpyxl 的 excel 中的單元格值

[英]If condition based on cell value in excel using Openpyxl

有兩個 excel 文件,其中條件數據應附加到另一個 excel 文件中。

條件:如果 A 列中的任何值等於“x”,那么它應該從 col B 獲取值並將其直接附加到 excel 文件 2 中的 col A/B。

下表顯示在 Excel 文件 1 中。

在此處輸入圖像描述

下面應該是輸出......它在 Excel 文件 2 中。

在此處輸入圖像描述

我對此很陌生..請幫助處理此代碼,最好是使用“Openpyxl”完成代碼,這將非常有幫助!

提前致謝。

對 Redox 的解決方案略有改進:

import openpyxl
#Open Input File open (file1)
wb1 = openpyxl.load_workbook('file1.xlsx')
ws1 = wb1['Sheet1']

wb2 = openpyxl.Workbook()
ws2 = wb2.active
ws2.append(["Base", "A/B"])

for row in ws1.iter_rows(min_row=2, max_col=3, values_only=True):
    base, a, b = row
    if a != "x":
        new_row = [base, a]
    else:
        new_row = [base, b]
    ws2.append(new_row)

理想情況下,您還應該檢查第三列是否具有有效值。

所以,一個簡單的解決方案和一個更復雜的解決方案:

在此處輸入圖像描述

然后在文件之間,您可以使用鏈接或索引()或間接()。

要使用 python-openpyxl 執行此操作,您可以使用以下代碼...添加注釋以便於理解...希望這會有所幫助。 如有問題請告訴我。

蟒蛇代碼

import openpyxl
#Open Input File open (file1)
wb1 = openpyxl.load_workbook('file1.xlsx')
ws1 = wb1['Sheet1']
#Create new file for Output (file2)
wb2 = openpyxl.Workbook()
ws2 = wb2.active
#Add header to output file
ws2.cell(row=1,column=1).value = "BASE"
ws2.cell(row=1,column=2).value = "A/B"

# Iterate through each line in input file from row 2 (skipping header) to last row
for row in ws1.iter_rows(min_row=2, max_row=ws1.max_row, min_col=1, max_col=3):
    for col, cell in enumerate(row):
        if col == 0: #First column, write to output
            ws2.cell(cell.row, col+1).value = cell.value
        elif col == 1:
            if cell.value != "X": #2nd column, write to output if not X
                ws2.cell(cell.row, col+1).value = cell.value
        else: #2nd column, write 3rd column if X
                ws2.cell(cell.row, col+1).value = ws1.cell(cell.row, col+2).value

wb2.save('file2.xlsx')

運行后輸出excel

在此處輸入圖像描述

暫無
暫無

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

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