【Python】【完整代码】解析Excel 文件中的内容并检查是否包含某字符串,并返回判断结果

示例:

开发需求:解析Excel 文件中的内容并检查是否包含 "Fail" 字符,若没有则返回True,若有则返回False

实现代码:

复制代码
#!/usr/bin/env python3
# -*- encoding: utf-8 -*-
'''
@File : check_excel_for_fail.py
@Time : 2024/02/1 11:30:13
@Author : jly
@Version : 1.0
@Software: Visual Studio Code
'''

import pandas as pd
import openpyxl

def check_excel_for_fail(file_path):
    try:
        # 读取 Excel 文件
        df = pd.read_excel(file_path)

        # 检查 DataFrame 中是否包含 "Fail" 字符
        if "Fail" not in df.to_string():
            return True
        else:
            return False

    except Exception as e:
        print(f"Error reading Excel file: {e}")
        return False

# 用法示例
file_path = "result.xlsx"
result = check_excel_for_fail(file_path)

if result:  #若result为True
    print("Excel file does not contain 'Fail'. Returning True.")
else:
    print("Excel file contains 'Fail'. Returning False.")

运行结果:

提示:

在这个示例中,`check_excel_for_fail` 函数读取 Excel 文件,将其转换为 Pandas 的DataFrame,并检查 DataFrame 中是否包含 "Fail" 字符。如果不包含,则返回 `True`,否则返回 `False`。确保安装了 `pandas` 和 `openpyxl`,可以使用以下命令安装:

bash 复制代码
pip install pandas openpyxl
相关推荐
SelectDB6 小时前
Apache Doris Python UDF:让 SQL 直接调用 Python 生态,支撑 Agent 时代复杂业务逻辑
大数据·数据库·python
荣码14 小时前
GraphRAG:普通RAG只能回答"点"的问题,我踩了4个坑才搞懂
java·python
金銀銅鐵1 天前
[Python] 基于欧几里得算法,实现分数约分计算器
python·数学
Lyn_Li1 天前
Kaggle Top 5 | 198只股票、200条数据的金融预测——BattleFin高分方案从零复现
python·kaggle·比赛复盘·金融预测
小九九的爸爸1 天前
前端想要入门Agent开发,要具备哪些Python基础?
python·agent·ai编程
阿耶同学1 天前
手把手教你用 LangGraph 搭建三层嵌套 Agent 架构
python·程序员
花酒锄作田2 天前
Pydantic校验配置文件
python
hboot2 天前
AI工程师第四课 - 深度学习入门
pytorch·python·神经网络
ZhengEnCi2 天前
P2M-Matplotlib折线图完全指南-从数据可视化到趋势分析的Python绘图利器
python·matlab·数据可视化
ZhengEnCi3 天前
P2L-Matplotlib饼图完全指南-从数据可视化到图表定制的Python绘图利器
python·matlab