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

Python实现将16选15组合写入xlsb文件并格式化(无括号、居中)

解决方案

直接用pandas处理组合数据,结合openpyxl设置单元格样式,以下是简洁实现:

import itertools
import pandas as pd
from openpyxl import load_workbook
from openpyxl.styles import Alignment

# 生成16选15的所有组合
numbers = list(range(1, 17))
combinations = list(itertools.combinations(numbers, 15))

# 转换为DataFrame,每个数字单独占一列
df = pd.DataFrame(combinations)

# 写入xlsb文件
output_file = "combinations.xlsb"
df.to_excel(output_file, index=False, header=False, engine="openpyxl")

# 加载文件并设置样式
wb = load_workbook(output_file)
ws = wb.active

# 设置所有单元格居中对齐
align_center = Alignment(horizontal="center", vertical="center")
for row in ws.iter_rows():
    for cell in row:
        cell.alignment = align_center

# 设置固定列宽(这里设为8,可根据需求调整)
for col in ws.columns:
    ws.column_dimensions[col[0].column_letter].width = 8

# 保存修改后的文件
wb.save(output_file)

关键说明:

  • 用pd.DataFrame(combinations)直接将元组列表转为表格结构,自动拆分每个数字到单独列,彻底避免原代码中括号、逗号的格式问题。
  • to_excel时指定index=False, header=False,去掉不必要的索引和表头,完全匹配每行一个组合的需求。
  • 通过openpyxl加载已生成的xlsb文件,批量设置单元格居中对齐和固定列宽,一次性完成格式调整。

内容的提问来源于stack exchange,提问作者ROCA

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 23:17:40