Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write dataframe to excel with a title

I would like to print out a dataframe in Excel. I am using ExcelWriter as follows:

writer = pd.ExcelWriter('test.xlsx')
df = DataFrame(C,ind)    # C is the matrix and ind is the list of corresponding indices 
df.to_excel(writer, startcol = 0, startrow = 5)
writer.save()

This produces what I need but in addition I would like to add a title with some text (explanations) for the data on top of the table (startcol=0 ,startrow=0).

How can I add a string title using ExcelWriter?

like image 928
Hamed Avatar asked Jan 13 '16 13:01

Hamed


People also ask

How do you write a DataFrame to an Excel?

Use pandas to_excel() function to write a DataFrame to an excel sheet with extension . xlsx. By default it writes a single DataFrame to an excel file, you can also write multiple sheets by using an ExcelWriter object with a target file name, and sheet name to write to.

Can you give a DataFrame a name?

Renaming column name of a DataFrame : We can rename the columns of a DataFrame by using the rename() function.

How do I give a sheet name a panda in Excel?

Step1: First Import the openpyxl library to the program. Step2: Load/Connect the Excel Workbook to the program. Step3: Use sheetnames property to get the names of all the sheets of the given workbook. Hope you have learned how to get the names of the sheets using the openpyxl in python from this article.


1 Answers

You should be able to write text in a cell with the write_string method, adding some reference to XlsxWriter to your code:

writer = pd.ExcelWriter('test.xlsx')
df = DataFrame(C,ind)    # C is the matrix and ind is the list of corresponding indices 
df.to_excel(writer, startcol = 0, startrow = 5)

worksheet = writer.sheets['Sheet1']
worksheet.write_string(0, 0, 'Your text here')

writer.save()
like image 146
Fabio Lamanna Avatar answered Sep 18 '22 20:09

Fabio Lamanna