Python 3.6实现Excel指定工作表指定列字符串搜索求助
完善你的Excel司机信息搜索自动化代码
嘿,作为编程新手想通过自动化提升办公效率,这个方向太赞了!我来帮你把这段代码补全,还加上了实用的容错逻辑,让它更稳定好用。
完整可运行代码
先给你直接能用的代码,后面再一步步解释细节:
import pandas as pd def search_driver_in_excel(): # 获取用户输入的文件路径、文件名和要搜索的司机名称 file_directory = input("Please enter file location (directory): ") file_name = input("Please enter the Excel file name (including .xlsx): ") driver_name = input("Please enter the driver name you want to search: ") # 拼接完整文件路径,兼容路径末尾是否带斜杠的情况 full_file_path = f"{file_directory}/{file_name}" if not file_directory.endswith('/') else f"{file_directory}{file_name}" try: # 读取Excel文件的第一个工作表 df = pd.read_excel(full_file_path, sheet_name=0) # 先检查目标列是否存在,避免报错 if "Current Driver" not in df.columns: print("Oops! Column 'Current Driver' wasn't found in the first worksheet. Please check the sheet structure.") return # 执行搜索:这里用模糊匹配(忽略大小写、跳过空值),如果要精确匹配可以改逻辑 matching_rows = df[df["Current Driver"].str.contains(driver_name, case=False, na=False)] # 给用户清晰的结果反馈 if matching_rows.empty: print(f"No records found for driver: {driver_name}") else: print(f"Great! Found {len(matching_rows)} records for driver: {driver_name}") print("\nHere are the matching details:") print(matching_rows) except FileNotFoundError: print(f"Error: Couldn't find the file at {full_file_path}. Please double-check the path and file name.") except Exception as e: print(f"Something unexpected went wrong: {str(e)}") # 启动搜索功能 search_driver_in_excel()
关键细节说明
- 路径兼容处理:自动适配用户输入的路径是否以斜杠结尾,避免拼接出
//这种错误路径 - 容错机制:
- 捕获文件不存在的情况,给明确的提示
- 检查「Current Driver」列是否存在,防止因为列名拼写错或者工作表结构变化导致崩溃
- 捕获其他未知异常,避免程序直接闪退
- 搜索逻辑灵活切换:
- 现在的代码是模糊匹配(比如输入“John”能找到“John Doe”“john smith”),
case=False忽略大小写,na=False跳过空值行 - 如果需要精确匹配,把搜索那行改成:
matching_rows = df[df["Current Driver"] == driver_name]
- 现在的代码是模糊匹配(比如输入“John”能找到“John Doe”“john smith”),
- 友好的结果反馈:不管找到没找到,都给用户清晰的信息,找到的话还会打印匹配的行数据
针对Python 3.6的注意事项
- 确保你安装了兼容的依赖包:Python 3.6支持的最新稳定pandas版本是1.1.5,同时需要openpyxl来读取xlsx文件,打开终端运行:
pip install pandas==1.1.5 openpyxl - 如果f-string用着有问题(理论上3.6支持),可以换成
os.path.join来拼接路径:import os full_file_path = os.path.join(file_directory, file_name)
内容的提问来源于stack exchange,提问作者Ariel Cruz
相关产品推荐
相关产品推荐

