繁体   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