使用Django+Pandas读取Excel双表头时无法识别商品表头的问题
Pandas读取Excel预算数据时无法识别商品项表头的解决办法
需求
使用Pandas读取Excel中的预算数据:
- Excel前两行对应Sorder类的表头及内容
- 第三行(Excel行号从1开始计数)是商品项的表头
输入数据示例
client payment_cond interest_discount_table price_list sorder_date requested_delivery_date 21101197111186 30/49 MT90 TEC9 01/11/2023 08/11/2023 product gross_price quantity LAAAAA1054 2 2 LAAAAA0962 3 3
问题
无法让Pandas正确识别商品项的新表头
当前实现代码
if excel_file.name.endswith('.xls') or excel_file.name.endswith('.xlsx'): try: df = pd.read_excel(excel_file) print("first two lines:") print(df.iloc[:1]) print("third line onwards:") df = pd.read_excel(excel_file, header=2) base_row = df.iloc[2] print(df.iloc[2:]) for index, row in df.iloc[2:].iterrows(): product = row['product'] gross_price = row['gross_price'] qtd = row['qtd'] product_base = base_row['product'] gross_price_base = base_row['gross_price'] qtd_base = base_row['qtd'] print(f"product: {product}, gross_price: {gross_price}, qtd: {qtd}")
问题分析与解决
核心问题
- 文件指针未重置:第一次调用
pd.read_excel后,文件对象的指针已移至末尾,第二次读取会获取空数据 - 表头设置错误:未正确指定商品表头所在的行索引,后续数据行的索引逻辑混乱
- 列名不匹配:代码中使用
qtd作为列名,但Excel表头是quantity,会触发KeyError
修正后的代码
import pandas as pd if excel_file.name.endswith(('.xls', '.xlsx')): try: # 1. 读取前两行的Sorder数据 sorder_df = pd.read_excel(excel_file, nrows=2, header=None) print("Sorder数据:") print(sorder_df) # 重置文件指针,确保第二次读取从开头开始 excel_file.seek(0) # 2. 读取商品数据:跳过前3行(Sorder两行+空行),用第4行作为表头 # 根据实际Excel结构调整skiprows和header参数 products_df = pd.read_excel(excel_file, skiprows=3, header=0) print("\n商品数据:") print(products_df) # 遍历商品数据 for index, row in products_df.iterrows(): product = row['product'] gross_price = row['gross_price'] qtd = row['quantity'] # 列名与Excel表头保持一致 print(f"product: {product}, gross_price: {gross_price}, qtd: {qtd}") except Exception as e: print(f"读取Excel失败:{str(e)}")
关键说明
- 文件指针重置:调用
excel_file.seek(0)让文件回到起始位置,保证第二次读取能获取完整内容 - 表头与跳过行:根据Excel实际结构调整参数:
- 若商品表头在Excel第3行(无空行分隔),则用
header=2,无需skiprows - 若有空白分隔行,用
skiprows跳过无关行,header=0表示用当前读取的第一行作为表头
- 若商品表头在Excel第3行(无空行分隔),则用
- 列名匹配:确保代码中使用的列名和Excel表头完全一致
内容的提问来源于stack exchange,提问作者Lucas Eduardo
相关产品推荐
相关产品推荐

