Skip to content

PyGWalker HTML 导出 API

当你需要静态 HTML 字符串时,使用 pygwalker.to_html(...)。静态导出仅支持浏览器计算:它不支持 live kernel 或 cloud 计算。

import pygwalker as pyg
 
html = pyg.to_html(
    df,
    spec_path="./gw_config.json",
    computation="browser",
)

静态 HTML 限制

静态 HTML 没有 live Python kernel,也没有云端回调。PyGWalker 会拒绝:

pyg.to_html(df, computation="kernel")
pyg.to_html(df, computation="cloud")
pyg.to_html(df, kernel_computation=True)
pyg.to_html(df, cloud_computation=True)
pyg.to_html(df, use_kernel_calc=True)

请使用 computation="browser" 或省略计算选项。需要 live kernel 或 cloud 计算时,请使用 Notebook APIStreamlitGradio 或 webserver 模式。

pygwalker.to_html

to_html 返回可嵌入的 iframe HTML 字符串。

import pathlib
import pygwalker as pyg
 
html = pyg.to_html(df, spec_path="./gw_config.json", computation="browser")
pathlib.Path("pygwalker.html").write_text(html, encoding="utf-8")

签名:

pyg.to_html(
    df,
    gid=None,
    *,
    spec="",
    spec_path=None,
    field_specs=None,
    theme_key="g2",
    appearance="media",
    default_tab="vis",
    computation=None,
    **kwargs,
) -> str

df 可以是 pandas DataFrame、polars DataFrame、pyarrow Table,或可复用的 pygwalker.Walker

从可复用 Walker 导出

当同一份图表状态也需要在 notebook 或应用中渲染时,请创建 Walker

import pygwalker as pyg
 
walker = pyg.Walker(
    df,
    spec_path="./gw_config.json",
    computation="browser",
)
 
html = pyg.to_html(walker, width="100%", height="720px")

to_html 接收 Walker 时,请通过 widthheight 关键字参数传入渲染尺寸。spec_pathfield_specsappearancecomputation 等构造选项必须设置在原始 Walker 上。

walker.to_html(iframe_width=None, iframe_height=None)walker.to_html_without_iframe() 提供相同的静态导出行为,也会拒绝 live kernel/cloud 计算。

表格和 renderer helper

当不需要完整探索器时,使用这些 helper。

from pygwalker.api.html import to_table_html, to_render_html
 
table_html = to_table_html(df, spec_path="./gw_config.json", computation="browser")
render_html = to_render_html(df, spec_path="./gw_config.json", computation="browser")

签名:

to_table_html(
    df,
    *,
    spec_path=None,
    theme_key="g2",
    appearance="media",
    computation=None,
    **kwargs,
) -> str
 
to_render_html(
    df,
    spec="",
    *,
    spec_path=None,
    theme_key="g2",
    appearance="media",
    computation=None,
    **kwargs,
) -> str

图表预览 helper

to_chart_html 会从 Graphic Walker 或 Vega spec 渲染单个图表。

from pygwalker.api.html import to_chart_html
 
chart_html = to_chart_html(
    df,
    spec=chart_spec,
    spec_type="graphic-walker",
)

签名:

to_chart_html(
    dataset,
    spec,
    *,
    spec_type="graphic-walker",
    theme_key="g2",
    appearance="media",
) -> str

dataset 可以是 DataFrame、pyarrow Table、数据库 Connector 或连接器式字符串。

常见陷阱

陷阱修复方式
使用 kernel 计算导出大型本地数据使用 live 后端,而不是静态 HTML。
Walkerspec_path 一起传给 to_htmlspec_path 放在 pyg.Walker(...) 上。
新静态示例仍以 kernel_computation=True 开始使用 computation="browser"
期望用户在静态导出中编辑并保存图表状态使用支持保存的 live notebook/app 后端,并设置 spec_io_mode="rw"

相关指南