You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Polars中使用write_excel时如何仅旋转最后三列表头列90°

Polars中使用write_excel时如何仅旋转最后三列表头列90°

嘿,这个需求其实很好实现!你之前用的header_format是全局统一设置所有表头的样式,所以会把所有列都转90度。想要只针对最后三列设置旋转,咱们可以用Polars提供的**header_formats参数**(注意是复数形式),它支持给单个列单独配置格式,完美适配你的场景。

具体步骤和代码示例如下:

  1. 先准备两种表头格式:一种是默认的常规样式,另一种是带90度旋转的样式
  2. 定位到DataFrame的最后三列
  3. 用header_formats字典给不同列分配对应的格式
import polars as pl

# 假设这是你的示例DataFrame(可以替换成你自己的数据集)
df = pl.DataFrame({
    "常规列1": [1, 2, 3],
    "常规列2": [4, 5, 6],
    "旋转列1": [7, 8, 9],
    "旋转列2": [10, 11, 12],
    "旋转列3": [13, 14, 15]
})

# 1. 定义两种表头格式(按需调整样式,比如加粗、居中)
# 常规表头格式
default_header = {
    "bold": True,
    "align": "center",
    "valign": "vcenter"
}
# 带90度旋转的表头格式
rotated_header = {
    "bold": True,
    "align": "center",
    "valign": "vcenter",
    "rotation": 90
}

# 2. 获取最后三列的列名
last_three_columns = df.columns[-3:]

# 3. 构建表头格式字典:先给所有列设默认格式,再覆盖最后三列的格式
header_formats = {}
for col in df.columns:
    header_formats[col] = default_header.copy()  # 用copy避免字典引用冲突
for col in last_three_columns:
    header_formats[col].update(rotated_header)

# 4. 写入Excel文件
df.write_excel("自定义表头样式.xlsx", header_formats=header_formats)

这样导出的Excel里,只有最后三列的表头会被旋转90度,其他列保持常规样式。如果你的样式需求更复杂,还可以在格式字典里添加更多属性(比如背景色、字体大小等),完全按需调整~

备注:内容来源于stack exchange,提问作者Andi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.14 14:09:32