Skip to main content

DaTraXLSX

这是一个把DataFrame保存为带有Excel格式的XLSX文件的工具。

安装

datraxlsx 需要Python 3.13及以上版本,依赖 openpyxl、pandas、polars。

# 本地开发安装
pip install -e .

# 或使用 uv
uv add datraxlsx

核心概念

datraxlsx 由四个可复用的构建块组成:

  • CellStyle — 可复用单元格样式,聚合 font/fill/alignment/border/number_format 五个字段(均可选),通过 apply(cell) 应用到单元格。
  • RowBorder — 以"边"描述一行单元格的边框:top/bottom/left_edge/right_edge/inner_vertical。它会自动区分左右边缘与内部竖线,无需手动处理首尾列。
  • TableTheme — 聚合 title/header/body/summary 四套 CellStyle 及其对应 RowBorder,外加 title_height/row_height/column_width。TableTheme.default() 开箱即用,.replace(...) 定制单个字段。
  • ExcelWriter + Sheet — 工作簿与工作表写入器。ExcelWriter 持有主题与游标起点,通过 .sheet(name) 创建工作表;Sheet 提供 use/write_title/write_data/write_summary/write_cell/set_column_width 等方法,支持多 sheet 写入。

快速开始

零配置即可写出带标题、表头、数据、合计行的格式化报表:

import pandas as pd
from datraxlsx import ExcelWriter

df = pd.DataFrame({"产品": ["A", "B", "C"], "数量": [10, 20, 30], "金额": [100.5, 200.5, 300.5]})

with ExcelWriter("output.xlsx") as wb:
    ws = wb.sheet("销售")
    ws.use(df)
    ws.write_title("销售报表")
    ws.write_data()
    ws.write_summary(agg_cols=["数量", "金额"], merge_cols=["产品"])

polars DataFrame 同样可用,use() 会自动转换。

复用主题

定义一次主题,跨 sheet、跨文件复用。TableTheme.default().replace(...) 只覆盖传入的字段,其余沿用默认值:

from datraxlsx import ExcelWriter, TableTheme, CellStyle, RowBorder
from openpyxl.styles import Font, PatternFill, Side

theme = TableTheme.default().replace(
    header=CellStyle(
        font=Font(name="微软雅黑", size=12, bold=True, color="FFFFFF"),
        fill=PatternFill(patternType="solid", fgColor="0066CC"),
    ),
    header_border=RowBorder(
        top=Side(border_style="thick"),
        bottom=Side(border_style="double"),
    ),
)

with ExcelWriter("output.xlsx", theme=theme) as wb:
    for name, df in sheets.items():
        ws = wb.sheet(name)
        ws.use(df)
        ws.write_title(name)
        ws.write_data()

按列名指定数字格式

write_data 与 write_summary 的 number_format 参数支持字符串(应用到所有列)或字典(按列名指定):

ws.write_data(number_format={"金额": "#,##0.00", "比例": "0.00%"})

一次性覆盖

每个写入方法都接受 style/border/height 等关键字参数,传入即覆盖该次调用的主题样式,不修改主题本身:

ws.write_data(body_style=CellStyle(font=Font(italic=True)))

API 速览

Sheet 方法(写入前须先调用 use(df)):

  • use(df, *, columns=None) — 绑定 DataFrame(pandas 或 polars),可选重排列或选取列子集。
  • write_title(text, *, crossline=0, style=None, border=None, height=None) — 写入跨列合并标题,crossline 控制跨行行数。
  • write_data(*, header_style=None, body_style=None, header_border=None, body_border=None, number_format=None, height=None) — 写入表头与数据行。
  • write_summary(*, agg_cols=None, pass_cols=None, agg_fun="sum", row_name="总计", merge_cols=None, pass_seq="--", style=None, border=None, number_format=None, height=None) — 写入合计行,agg_cols 求和、pass_cols 填占位符、merge_cols 合并前导列。
  • write_cell(range, value=None, *, style=None, height=None) — 写入或合并写入任意单元格区域,range 支持 "A1" 或 "A1:C3"。
  • set_column_width(width, *, columns=None) — 设置列宽,columns 省略则全部列,可传列名或列名列表。

ExcelWriter 方法:

  • ExcelWriter(filename, *, theme=None, start_row=1, start_col=1) — 构造工作簿,可指定主题与写入起点。
  • .sheet(name=None, *, show_gridlines=False) — 创建工作表,默认隐藏网格线。
  • .save() — 保存文件;作为上下文管理器使用时退出即保存。

工具函数

transColname2Letter(colnames, xlsDataRange) 将列名映射到 Excel 列字母。传入列名列表与对应的 Excel 区域字符串(如 "A1:D10"),返回 {列名: 列字母} 字典。列名数量须与区域列数一致,否则抛出 ValueError。

Metadata

Release files for datraxlsx 0.3.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for datraxlsx 0.3.0
File Size Uploaded
datraxlsx-0.3.0.tar.gz 6.2 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for datraxlsx 0.3.0
File Interpreter ABI Platform
datraxlsx-0.3.0-py3-none-any.whl Python 3 none any Details

Total release size: 13.7 kB

Release files / datraxlsx-0.3.0.tar.gz

Download URL datraxlsx-0.3.0.tar.gz
Size 6.2 kB
Tags Source
SHA-256 checksum
How to use checksums
3c38f96ba77df870f9764d7b85867f7ce07331fdcbcada5e0c183b567243476d
BLAKE2b-256 checksum
How to use checksums
3c5225a2f906f07583bc55e65723c81188c264f18dbe481eb572290b2ba2a7ee
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.11.26 {"installer":{"name":"uv","version":"0.11.26","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":null,"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Release files / datraxlsx-0.3.0-py3-none-any.whl

Download URL datraxlsx-0.3.0-py3-none-any.whl
Size 7.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
79e1370e101cb8267f925f2fa696b48fb781d18d9efbd3cc4e38235305e14ceb
BLAKE2b-256 checksum
How to use checksums
b22c3baa94222efe94fe14db83b6ce47c9612128f34cc11615ed31058e22ad58
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.11.26 {"installer":{"name":"uv","version":"0.11.26","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":null,"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Release history Release notifications | RSS feed

This release

0.3.0 This release

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page