如何遍历excel工作表并使用python在每张工作表上执行相同的任务

问题描述 投票:0回答:1

我有一个包含很多行数据的excel文件。我还有第二张文件,里面有多张纸。使用python,我想遍历第二个文件中的每个工作表,并将其与第一个文件中的数据合并(它们具有相同的列标题)。

作为最终导出,我希望将所有合并的数据放回到第一个文件中。

我对python比较陌生,除了在pandas库和两个文件中读取之外,没有编写任何代码。

python loops merge
1个回答
0
投票

鉴于file1.xlsx是您的主文件,file2.xlsx是您的具有多张纸的文件:

import pandas

df_main = pd.read_excel('file1.xlsx')
multiple_sheets = pd.read_excel('file2.xlsx', sheet_name=None)  # None means all sheets, this produces a dict of DataFrames with the keys as the sheet names.

for x in multiple_sheets.values():  # Loop through dict with x as the df per sheet
    # Cleanup before adding.
    df_main = pd.concat([df_main, x], ignore_index=True)

[从现在开始,您可以进行清理并将DataFrame保存为新的Excel文件(即df_main.to_excel('file1.xlsx'))。

参考文献:

© www.soinside.com 2019 - 2024. All rights reserved.