Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I save multiple dataframes onto one excel file (as separate sheets) without this error occurring?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading