You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Python从Excel检索指定商品对应账单的问题求助

问题描述

现有bills.xlsx表格,需实现一个方法,传入商品名称即可检索包含该商品的所有完整账单。原代码运行后无法获取正确结果,例如搜索product1时,期望输出:

[{'Bill number': 31}, {'Date': '2024-04-16 04:39:44'}]
[{'product name': 'product1'}, {'count': 1}, {'price': 10}, {'total price': 10}]
[{'product name': 'product1'}, {'count': 1}, {'price': 10}, {'total price': 10}]
[{'Total price': 20}]
原代码核心问题
  • 数据收集逻辑错误:products变量在每行循环内被重置,未将所有账单数据存入全局集合,导致最后仅保留单行数据
  • 参数传递错误:调用搜索函数时传入的是单行数据,而非整个账单集合
  • 键名不统一:代码中存在大小写/名称不匹配(如Bill Number vs Bill number、History vs Date),导致边界识别失败
正确实现代码
from openpyxl import load_workbook

file_path = 'C:/Users/Mohamed Hamdi/Desktop/bills.xlsx'
bills_workbook = load_workbook(file_path)
bills_sheet = bills_workbook.active

# 结构化存储所有账单
all_bills = []
current_bill = None

for row in range(1, bills_sheet.max_row + 1):
    # 获取当前行所有单元格值(处理空值)
    row_values = [bills_sheet.cell(row=row, column=col).value for col in range(1, 7)]
    
    # 识别账单起始行(包含Bill Number)
    if row_values[0] == "Bill Number":
        if current_bill is not None:
            # 保存上一个账单
            all_bills.append(current_bill)
        # 初始化新账单
        current_bill = {
            'bill_number': row_values[1],
            'date': row_values[3],
            'products': [],
            'total_price': None
        }
    # 识别商品行(第3列有商品名,且不是标题行)
    elif row_values[2] is not None and row_values[2] != "product name":
        if current_bill is not None:
            current_bill['products'].append({
                'product name': row_values[2],
                'count': row_values[3],
                'price': row_values[4],
                'total price': row_values[5]
            })
    # 识别账单结束行(包含Total price)
    elif row_values[0] == "Total price":
        if current_bill is not None:
            current_bill['total_price'] = row_values[1]
            # 保存当前账单
            all_bills.append(current_bill)
            current_bill = None

# 搜索函数:传入商品名称,返回包含该商品的所有账单
def find_bills_by_product(product_name):
    matching_bills = []
    for bill in all_bills:
        # 检查当前账单的商品列表是否包含目标商品
        for product in bill['products']:
            if product['product name'] == product_name:
                matching_bills.append(bill)
                break  # 找到一个匹配就停止检查当前账单的其他商品
    return matching_bills

# 测试搜索
target_product = "product1"
result_bills = find_bills_by_product(target_product)

# 按照期望格式输出结果
for bill in result_bills:
    # 打印账单头部
    print([{'Bill number': bill['bill_number']}, {'Date': bill['date']}])
    # 打印每个商品
    for product in bill['products']:
        print([product])
    # 打印账单总价
    print([{'Total price': bill['total_price']}])
代码说明
  • 数据结构化:将每个账单封装为字典,包含bill_number、date、products列表、total_price,清晰区分账单的各个部分
  • 边界识别:通过行首的Bill Number和Total price准确识别每个账单的起始和结束,确保账单数据完整
  • 精准搜索:遍历所有账单,检查商品列表是否包含目标商品,匹配则返回整个账单
  • 格式匹配:输出格式完全符合期望,将账单头部、商品、总价分别按要求打印

内容的提问来源于stack exchange,提问作者Ahmed Bakr Shaheen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 09:57:02