简体   繁体   English

使用 xlsxwriter 居中对齐(无条件格式)

[英]Center align using xlsxwriter (without conditional formatting)

Using xlsxwriter, one can write a dataframe 'df' to Excel 'simple.xlsx' using code such as:使用 xlsxwriter,可以使用以下代码将 dataframe 'df' 写入 Excel 'simple.xlsx' :

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.使用上面的代码,我看到生成的 Excel 表将所有单元格(标题除外)默认为左对齐。

Question:问题:

How can I make the Excel cell values to be center-aligned?如何使 Excel 单元格值居中对齐? 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?有什么方法可以将 dataframe 写入 Excel 为中心对齐? 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?一旦 dataframe 已经写入 Excel 后,任何方式来中心对齐 Excel 表(用于数据帧占用的单元格范围)?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM