CORE
图表
docx 和 pptx 共享的图表组件 — 支持 11 种图表类型
@office-open/core 提供了 @office-open/docx 和 @office-open/pptx 共享的图表组件。图表通过 ChartSpaceOptions 定义,由 chartSpaceDesc 描述符进行序列化和解析。图表数据由 ChartCollection 管理。
图表类型
type 属性选择图表类型:
| 类型 | 值 | 说明 |
|---|---|---|
| 柱状图 | "column" | 垂直柱状 |
| 条形图 | "bar" | 水平柱状 |
| 折线图 | "line" | 带可选标记的折线系列 |
| 饼图 | "pie" | 饼图 |
| 面积图 | "area" | 填充面积系列 |
| 散点图 | "scatter" | XY 散点图 |
| 圆环图 | "doughnut" | 环形图 |
| 雷达图 | "radar" | 雷达/蜘蛛图 |
| 气泡图 | "bubble" | 气泡图(需 xValues/yValues/bubbleSize) |
| 股票图 | "stock" | 股价图(高低收) |
| 曲面图 | "surface" | 3D 曲面图 |
设置 threeD: true 可将 column、bar、line、pie、area 转为 3D 变体。
ChartSpaceOptions
ChartSpaceOptions 是图表的选项接口。它指定图表类型、标题、坐标轴和数据:
import type { ChartSpaceOptions } from "@office-open/core";
const chartOptions: ChartSpaceOptions = {
title: "营收",
type: "bar",
categories: ["Q1", "Q2", "Q3", "Q4"],
series: [{ name: "2024", values: [10, 20, 30, 40] }],
};
选项
| 选项 | 类型 | 说明 |
|---|---|---|
type | ChartType | 图表类型字符串(见上表) |
categories | string[] | 类别标签 |
series | ChartSeriesData[] | BubbleSeriesData[] | 系列数据 |
title | string | 图表标题 |
showLegend | boolean | 是否显示图例(默认:true) |
style | number | 样式预设(2–48) |
threeD | boolean | 启用 3D 渲染 |
chartSpaceDesc
chartSpaceDesc 是 CustomDescriptor<ChartSpaceOptions>,负责图表 XML(c:chartSpace)的序列化和解析。docx 和 pptx 包内部使用此描述符:
import { chartSpaceDesc } from "@office-open/core";
import { stringify, parse } from "@office-open/core/descriptor";
// 序列化图表选项为 XML
const xml = stringify(chartSpaceDesc, chartOptions, writeCtx);
// 解析图表 XML 回选项对象
const options = parse(chartSpaceDesc, chartElement, readCtx);
ChartCollection
ChartCollection 管理文档或演示文稿中的多个图表。它按 ID 存储 ChartData 条目:
import { ChartCollection } from "@office-open/core";
const charts = new ChartCollection();
charts.addChart("chart1", { key: "chart1", chartSpaceXml: xml });
ChartData
| 属性 | 类型 | 说明 |
|---|---|---|
key | string | 唯一图表 ID |
chartSpaceXml | string | 序列化的图表 XML |
系列数据
每种图表类型接受系列数据,包含类别标签和值。标准系列使用 ChartSeriesData:
const series: ChartSeriesData[] = [
{ name: "产品 A", values: [10, 20, 15] },
{ name: "产品 B", values: [5, 12, 8] },
];
ChartSeriesData
| 选项 | 类型 | 说明 |
|---|---|---|
name | string | 系列名称 |
values | number[] | 数据值 |
trendlines | TrendlineOptions[] | 系列趋势线 |
errorBars | ErrorBarOptions | 误差线配置 |
dataLabels | DataLabelsOptions | 数据标签配置 |
气泡图使用 BubbleSeriesData:
| 选项 | 类型 | 说明 |
|---|---|---|
name | string | 系列名称 |
xValues | number[] | X 坐标 |
yValues | number[] | Y 坐标 |
bubbleSize | number[] | 气泡大小 |
坐标轴
使用坐标轴的图表(柱状、折线、面积、散点)会根据图表类型自动创建坐标轴。坐标轴配置在序列化期间内部处理。
在文档中使用
图表通常通过文档/演示文稿 API 创建,而非直接使用。参见: