首页 > 解决方案 > Write multiple files to excel using pandas &excelwriter

问题描述

The list of dataframes

df_list = [summary, df3, df4, df5, df6]

Names of excel sheets where the output has to be written

Names = ['Liability','Expenses','Income','Asset']

writer = pd.ExcelWriter(r"E:\GL\2040001.xlsx", engine='xlsxwriter')

If a dataframe has output then the file has to be written to excel

for i in df_list: if i.empty is False: for j in Names: i.to_excel(writer, sheet_name = j)

I want the files which are not empty to be written with its corresponding dataframe

标签: pandasloopsfor-loopexport-to-excel

解决方案


您只需要检查数据框是否为空。如果是,你什么也不做。如果不是,则写入 Excel:

df_list = [summary, df3, df4, df5, df6]
names = ['Liability','Expenses','Income','Asset']
writer = pd.ExcelWriter(r"E:\GL\2040001.xlsx", engine='xlsxwriter')
for df, name in zip(df_list, names):
    if not df.is_empty:
        df.to_excel(writer, sheet_name = name)

请注意,Python 中的变量名最好是小写的。另外,尽量不要使用绝对路径,而是使用相对路径。


推荐阅读