Pythonista anonymous
Pythonista anonymous

Reputation: 8950

python pandas: manually write to the same Excel after exporting a dataframe

I export a dataframe to Excel this way:

import pandas as pd
df=pd.DataFrame( data= np.ones((4,2)), columns=['x','y'])

writer = pd.ExcelWriter('output.xlsx')
sheet='Test'
df.to_excel(writer,sheet)

writer.save()

How can I get python to write a few lines of description to the right of the dataframe? Something like: "this dataframe contains bla bla bla". Specifically:

  1. Can I use pandas to write to the same sheet? Or do I have to use another module after writer.save()? Saving and reopening seems like a waste of time and resources
  2. If I cannot use pandas, what module shall I use? xlsxwriter cannot modify existing file.

Upvotes: 2

Views: 766

Answers (1)

chrisb
chrisb

Reputation: 52246

You can access the XlsxWriter workbook/worksheet before saving and do any modifications you want there. E.g.

df.to_excel(writer, sheet)
wb = writer.book
ws = writer.sheets[sheet]
ws.write(1, 4, "DataFrame contains ...")
writer.save()

Upvotes: 2

Related Questions