python-3.x 如何通过多个条件遍历excel文件

ve7v8dk2  于 2023-06-25  发布在  Python
关注(0)|答案(1)|浏览(92)

我有以下脚本:

import openpyxl
from openpyxl.styles import PatternFill

def process_excel_file(file_path, sheet_name):
    # Load the Excel file
    workbook = openpyxl.load_workbook(file_path)
    # Select the specified sheet
    sheet = workbook[sheet_name]

    # Define color styles
    orange_fill = PatternFill(start_color="FFA500", end_color="FFA500", fill_type="solid")
    dark_red_fill = PatternFill(start_color="8B0000", end_color="8B0000", fill_type="solid")

    # Loop through each row in column B and C, skipping the first 4 rows
    for row in sheet.iter_rows(min_row=5, min_col=2, max_col=3):
        column_b_value, column_c_value = row[0].value, row[1].value

        # Check conditions and apply cell color
        if column_b_value and column_c_value:
            print(f"Column B: {column_b_value}\tColumn C: {column_c_value}")
        elif column_b_value and not column_c_value:
            sheet.cell(row=row[1].row, column=row[1].column).fill = orange_fill
        elif not column_b_value and column_c_value:
            sheet.cell(row=row[0].row, column=row[0].column).fill = orange_fill
        else:
            sheet.cell(row=row[0].row, column=row[0].column).fill = dark_red_fill
            sheet.cell(row=row[1].row, column=row[1].column).fill = dark_red_fill

    # Save the modified workbook
    modified_file_path = '/xxx/updated.xlsx'
    workbook.save(modified_file_path)

    # Close the workbook
    workbook.close()

# Specify the file path and sheet name
file_path = 'myfile.xlsx'
sheet_name = 'test'

# Call the function to process the Excel file
process_excel_file(file_path, sheet_name)

虽然我不能正确理解我想要遵循的逻辑。

  • 如果B列和C列中有数据,则同一行打印数据。
  • 如果B列中有数据但C列中没有数据,则将C列中的空单元格在同一行中显示为橙色。
  • 如果C列中有数据但B列中没有数据,则将B列中的空单元格在同一行中显示为橙色。
  • 如果在B列或C列中没有数据,则相同行将B列和C列单元格着色为暗红色。

先谢谢你

zbwhf8kr

zbwhf8kr1#

你可以用

my_red = openpyxl.styles.colors.Color(rgb='00FF0000')
my_fill = openpyxl.styles.fills.PatternFill(patternType='solid', fgColor=my_red)
cell.fill = my_fill

来填充一个单元格。如果在顶部添加两个填充:

orange_fill= openpyxl.styles.fills.PatternFill(patternType='solid', fgColor=openpyxl.styles.colors.Color(rgb='00FFA500'))
red_fill = openpyxl.styles.fills.PatternFill(patternType='solid', fgColor=openpyxl.styles.colors.Color(rgb='00FF0000'))

然后你的条件是这样的:

# Check conditions and print values
if column_b_value is not None and column_c_value is not None:
  print(f"Column B: {column_b_value}\tColumn C: {column_c_value}")

else if column_b_value is None and column_c_value is not None:
  row[0].fill = orange_fill

else if column_b_value is not None and column_c_value is None:
  row[1].fill = orange_fill

else:
  row[0].fill = red_fill
  row[1].fill = red_fill

相关问题