Home > Blockchain >  How can I save multiple dataframes onto one excel file (as separate sheets) without this error occur
How can I save multiple dataframes onto one excel file (as separate sheets) without this error occur

Time:05-17

I have the following Python code:

import pandas as pd
path=r"C:\Users\Wali\Example.xls"
df1=pd.read_excel(path, sheet_name = [0])
df2=pd.read_excel(path, sheet_name = [1])

with pd.ExcelWriter(r"C:\Users\Wali\Example2.xls") as writer:

    # use to_excel function and specify the sheet_name and index
    # to store the dataframe in specified sheet
    df1.to_excel(writer, sheet_name="1", index=0)
    df2.to_excel(writer, sheet_name="2", index=1)

I'm reading the excel file which contains two sheets and then saving those sheets into a new excel file but unfortunately I'm receiving the following error:

AttributeError: 'dict' object has no attribute 'to_excel'

Any ideas on how I can fix this?. Thanks.

CodePudding user response:

Change [0] to 0 in pd.read_excel(path, sheet_name = [0]) will resolve this issue

import pandas as pd
path=r"test_book.xlsx"
df1=pd.read_excel(path, sheet_name = 0)
df2=pd.read_excel(path, sheet_name = 1)

with pd.ExcelWriter(r"test_book1.xlsx") as writer:

    # use to_excel function and specify the sheet_name and index
    # to store the dataframe in specified sheet
    df1.to_excel(writer, sheet_name="1", index=0)
    df2.to_excel(writer, sheet_name="2", index=1)
  • Related