2

Im trying to create an excel file with pandas for a database I have generated.

I have tried both:

import pandas as pd

# write database to excel
df = pd.DataFrame(database)

# Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter('fifa19.xlsx', engine='xlsxwriter')

# Convert the dataframe to an XlsxWriter Excel object.
df.to_excel(writer, sheet_name='Sheet1')

# Close the Pandas Excel writer and output the Excel file.
writer.save()

as well as:

import pandas as pd
df = pd.DataFrame(database).T 
df.to_excel('database.xls')

However, none of the options generate an excel file. Database is a dictionary.

7
  • 3
    Your code works fine for me. The file is created in the current working directory of the interpreter; i.e. the output of os.getcwd() -- perhaps you're looking in the wrong place?
    – fuglede
    Nov 3, 2018 at 12:45
  • @fuglede You were right. It got saved to a completely different location. Is there a simple way to change that so it saves to the same directory as the file? Nov 3, 2018 at 13:03
  • 1
    @AntonÖdman You can use os.chdir to change the working directory, but depending on how you're using this, chances are that you're better off by specifying the absolute path in the argument to ExcelWriter.
    – fuglede
    Nov 3, 2018 at 13:06
  • simple writer = pd.ExcelWriter('/home/anton/newoutput.xlsx') , however you don't need to mention engine='xlsxwriter' in the newwer version of pandas.
    – Karn Kumar
    Nov 3, 2018 at 13:07
  • @AntonÖdman , i think its not good to call extra module to change the path even when we can explicitly mention the path during the write of new file until its mandatory for some reasons.
    – Karn Kumar
    Nov 3, 2018 at 13:10

1 Answer 1

6

From the pandas document Notes itself:

If passing an existing ExcelWriter object, then the sheet will be added to the existing workbook. This can be used to save different DataFrames to one workbook:

>>> writer = pd.ExcelWriter('output.xlsx')
# writer = pd.ExcelWriter('/path_to_save/output.xlsx')
>>> df1.to_excel(writer,'Sheet1')
>>> df2.to_excel(writer,'Sheet2')
>>> writer.save()

For compatibility with to_csv, to_excel serializes lists and dicts to strings before writing.

1
  • 1
    Thanks for this. The code I had (written by someone else) worked fine for some time, but for some reason stopped working (may have been due to environment changes). Turned out the code didn't have the 'writer.save()' line. Now it works :) Sep 30, 2020 at 15:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.