Python先读取一个excel中给出的两列文字,然后用IFS函数筛选出另一个excel中对应的两列包含这部分文字的表格,最后在新的excel中做出红色标记输出。
时间: 2025-04-06 07:12:59 浏览: 29
### 使用Python处理Excel文件并应用IFS逻辑
要完成此任务,可以利用 `pandas` 和 `openpyxl` 库来读取 Excel 文件、筛选数据以及对符合条件的结果进行标记。以下是详细的解决方案:
#### 方法概述
1. **读取源数据**:使用 `pandas.read_excel()` 函数加载两个 Excel 文件的内容。
2. **实现 IFS 逻辑**:通过 Pandas 的条件过滤功能模拟 Excel 中的 IFS 函数行为。
3. **创建新工作簿**:使用 `openpyxl` 创建新的 Excel 工作簿并将结果写入其中。
4. **设置单元格样式**:对于满足特定条件的数据,在目标 Excel 文件中将其字体颜色设为红色。
下面是具体的代码实现:
```python
import pandas as pd
from openpyxl import Workbook
from openpyxl.styles import Font
# 步骤一:读取两个 Excel 文件
df_source = pd.read_excel('source.xlsx', usecols=['ColumnA', 'ColumnB']) # 替换为实际列名
df_reference = pd.read_excel('reference.xlsx', usecols=['RefColumnA', 'RefColumnB'])
# 步骤二:定义 IFS 条件逻辑
def ifs_logic(row, ref_df):
condition_1 = (ref_df['RefColumnA'] == row['ColumnA']).any()
condition_2 = (ref_df['RefColumnB'] == row['ColumnB']).all() # 假设 ColumnB 是列表形式
if condition_1 and condition_2:
return True
return False
# 将逻辑应用于 DataFrame 并生成结果标志
df_result = df_source.copy()
df_result['Matched'] = df_result.apply(lambda x: ifs_logic(x, df_reference), axis=1)
# 步骤三:保存到新的 Excel 文件
wb = Workbook()
ws = wb.active
# 写入标题行
ws.append(['ColumnA', 'ColumnB', 'Matched'])
# 遍历结果并写入数据
for _, row in df_result.iterrows():
ws.append([row['ColumnA'], row['ColumnB'], row['Matched']])
last_row = ws.max_row
if row['Matched']:
ws[f'C{last_row}'].font = Font(color="FF0000") # 设置匹配项的颜色为红色
# 保存文件
wb.save('output_with_red_markings.xlsx')
```
上述代码实现了以下功能:
- 利用 Pandas 加载和操作 Excel 数据[^1]。
- 定义了一个自定义函数 `ifs_logic` 模拟 Excel 的 IFS 行为[^2]。
- 结合 Openpyxl 对输出文件中的某些单元格进行了特殊格式化。
#### 注意事项
- 如果输入的 Excel 文件较大,则可能需要优化内存管理方式以提高性能。
- 上述示例假设了简单的条件判断;如果实际情况更加复杂,请调整 `ifs_logic` 函数内的逻辑。
---
###
阅读全文
相关推荐


















