Python代码:根据Excel单号查询并输出结果
以下是一个根据Excel表中的单号查询结果并将结果输入到Excel表中的Python代码示例:
import pandas as pd
# 读取原始数据的Excel表格
df_original = pd.read_excel('原始数据.xlsx')
# 创建一个新的Excel表格用于存储查询结果
df_result = pd.DataFrame(columns=df_original.columns)
# 需要查询的单号列表
order_numbers = ['order1', 'order2', 'order3']
# 遍历原始数据表格,查找匹配的单号并添加到结果表格
for index, row in df_original.iterrows():
if row['单号'] in order_numbers:
df_result = df_result.append(row)
# 将结果写入新的Excel表格
df_result.to_excel('查询结果.xlsx', index=False)
请确保将代码中的'原始数据.xlsx'替换为您实际的原始数据文件名,并将'查询结果.xlsx'替换为您希望保存查询结果的文件名。
代码的步骤如下:
- 导入
pandas库用于处理Excel数据。 - 使用
pd.read_excel()函数读取原始数据的Excel表格,并将数据存储在名为df_original的DataFrame中。 - 创建一个名为
df_result的空DataFrame,用于存储查询结果。 - 根据您的需求,将需要查询的单号列表存储在
order_numbers变量中。 - 使用
iterrows()方法遍历原始数据表格的每一行,并检查每行的'单号'是否在order_numbers列表中。 - 如果某个单号在
order_numbers列表中,则将该行添加到df_result中。 - 使用
to_excel()方法将查询结果保存到名为'查询结果.xlsx'的Excel表格中。
请确保您已经安装了pandas库(可以使用pip install pandas命令进行安装)再运行以上代码。
原文地址: https://www.cveoy.top/t/topic/CZ5 著作权归作者所有。请勿转载和采集!