擅长:python、mysql、java
<p>您可以使用<a href="https://pandas.pydata.org/docs/reference/api/pandas.io.formats.style.Styler.html#pandas.io.formats.style.Styler" rel="nofollow noreferrer">Styler object</a>设置数据帧的样式,它使用与CSS相同的约定。<a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/style.html" rel="nofollow noreferrer">documentation</a>有一本关于数据帧的不同样式的入门书</p>
<p>对于示例的简单解决方案,您可以通过首先创建函数来设置所需的对齐方式:</p>
<pre><code>def align_center(x):
return ['text-align: center' for x in x]
</code></pre>
<p>然后在应用刚刚定义的函数时将其写入Excel:</p>
<pre><code>with pd.ExcelWriter("test.xlsx") as writer:
df.style.apply(align_center, axis=0).to_excel(
writer,
index=False,
header=False
)
</code></pre>
<p>这将使Excel文件中的单元格居中对齐。关于可用文本对齐选项的详尽列表,我建议使用<a href="https://developer.mozilla.org/en-US/docs/Web/CSS/text-align" rel="nofollow noreferrer">MDN docs</a></p>