Home » excel » python – Center align using xlsxwriter (without conditional formatting)

python – Center align using xlsxwriter (without conditional formatting)

Posted by: admin May 14, 2020 Leave a comment

Questions:

Using xlsxwriter, one can write a dataframe ‘df’ to Excel ‘simple.xlsx’ using code such as:

import pandas as pd
writer = pd.ExcelWriter('simple.xlsx', engine='xlsxwriter')
df.to_excel(writer, sheet_name='Sheet1')
writer.save()

With above code, I see that the resultant Excel sheet has all cells (except header) as default left-aligned.

Question:

How can I make the Excel cell values to be center-aligned?
I did explore using conditional formatting but, with my cell values being combination of blanks, zeros, floats, strings and integers, I am wondering if there is another way.
Is there a smarter/quick way to do either/both of the following:

  • Any way to write dataframe to Excel as center-aligned? Or..

  • Any way to center-align the Excel sheet (for the cell range occupied by dataframe) once the dataframe has already been written to Excel?

How to&Answers:

You can add the below line to your code

df=df.style.set_properties(**{'text-align': 'center'})

Your complete code would be

import pandas as pd
writer = pd.ExcelWriter('simple.xlsx', engine='xlsxwriter')
df=df.style.set_properties(**{'text-align': 'center'})
df.to_excel(writer, sheet_name='Sheet1')
writer.save()