【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
相关推荐
cup111 小时前
[技术复盘] Windows Python 打包实战:Nuitka 环境踩坑总结与 CI 自动化构建全指南
python·ai·环境变量·ci·nuitka·skill
aqi003 小时前
15天学会AI应用开发(七)有了大模型为什么还要引入RAG
人工智能·python·大模型·ai编程·ai应用
金銀銅鐵5 小时前
用 Python 实现 Take-Away 游戏
python·游戏
copyer_xyf6 小时前
Agent 流程编排
后端·python·agent
copyer_xyf6 小时前
Agent RAG
后端·python·agent
copyer_xyf6 小时前
【RAG】向量数据库:milvus
后端·python·agent
copyer_xyf6 小时前
Agent 记忆管理
后端·python·agent
星云穿梭1 天前
用Python写一个带图形界面的学生管理系统——完整教程
python
金銀銅鐵1 天前
用 Pygame 实现 15 puzzle
python·数学·游戏