Sinha
Sinha

Reputation: 456

Center align using xlsxwriter (without conditional formatting)

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:

Upvotes: 2

Views: 5923

Answers (1)

moys
moys

Reputation: 8033

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()

Upvotes: 2

Related Questions