Charts and other objects¶
Charts, formulas, notes, links, images, pivots and printing.
Chart
dataclass
¶
Chart(chart_type: str, series: list[ChartSeries] | tuple[ChartSeries, ...], title: str | None = None, anchor: str = 'E2', width: float = 15.0, height: float = 7.5, style: int | None = None, x_axis: ChartAxis | None = None, y_axis: ChartAxis | None = None, y2_axis: ChartAxis | None = None, legend: ChartLegend | bool | None = None, data_labels: DataLabels | None = None, show_data_labels: bool = False, title_size: float | None = None, grouping: str | None = None, gap_width: int | None = None, hole_size: int | None = None, fill: str | None = None, border: str | None = None, plot_fill: str | None = None, font_size: float | None = None, font_color: str | None = None)
A chart anchored to a cell of the sheet it is written to.
x_axis is the category (or X value) axis and y_axis the value axis,
whatever the orientation: in a horizontal bar chart the category axis is
drawn vertically but is still x_axis.
legend accepts None (default, right-hand legend), False (no
legend), True (default legend) or a ChartLegend.
grouping stacks the series of a bar, horizontal bar, line or area
chart: "stacked" adds them up, "percent_stacked" shows each
category as 100%. None (default) draws them side by side.
A chart mixes types when some series set ChartSeries.chart_type (bar,
line and area only); series with secondary_axis use y2_axis, the
value axis on the right.
Examples:
A bar chart over a written range:
from xlspy import Chart, ChartSeries, Style, XlsxWriter
rows = [["Region", "Q1", "Q2"], ["North", 120, 140], ["South", 90, 110]]
with XlsxWriter("chart.xlsx") as workbook:
workbook.add_sheet("Data")
workbook.write_sheet(
rows,
header_style=Style(bold=True),
charts=[
Chart(
"bar",
[ChartSeries("B2:C3", categories="A2:A3", title="Quarter")],
title="Sales by region",
anchor="E2",
)
],
)
A line chart with formatted value axis and data labels:
Chart(
"line",
[ChartSeries("B2:B13", title="Actual"), ChartSeries("C2:C13", title="Plan")],
title="Trend",
y_axis=ChartAxis(title="Revenue", number_format="#,##0"),
show_data_labels=True,
anchor="E18",
)
See Also
ChartSeries, ChartAxis, ChartLegend, ChartMarker, DataLabels,
Trendline and ErrorBars for the nested options.
series_types
property
¶
series_types: list[str]
The distinct types the series are drawn as, in series order.
uses_extended_features
property
¶
uses_extended_features: bool
True when the chart uses anything beyond the original model.
The XLSB writer uses this to reject, rather than silently drop, the options it does not serialize.
ChartSeries
dataclass
¶
ChartSeries(values: str, title: str | None = None, title_cell: str | None = None, categories: str | None = None, x_values: str | None = None, color: str | None = None, marker: ChartMarker | None = None, line: bool | None = None, chart_type: str | None = None, secondary_axis: bool = False, trendline: Trendline | None = None, error_bars: ErrorBars | None = None)
One data series of a Chart.
categories labels the points of bar, line and pie series. x_values
gives the numeric X positions of a scatter series. color is the fill of
bars and pie slices, and the line or marker colour of line and scatter
series. marker and line apply to line and scatter series only.
In a combined chart chart_type ("bar", "line" or "area")
draws this series as another type than the chart's, and secondary_axis
reads it against a second value axis on the right.
ChartAxis
dataclass
¶
ChartAxis(title: str | None = None, minimum: float | None = None, maximum: float | None = None, major_unit: float | None = None, number_format: str | None = None, gridlines: bool | None = None, reverse: bool = False, visible: bool = True)
Settings for one chart axis.
gridlines defaults to on for the value axis and off for the category
or X axis when left as None.
ChartLegend
dataclass
¶
ChartLegend(position: str = 'right', overlay: bool = False)
Legend placement; overlay lets the legend cover the plot area.
ChartMarker
dataclass
¶
ChartMarker(symbol: str = 'circle', size: int = 7)
Marker shape for line and scatter series.
The marker is filled with the series color.
DataLabels
dataclass
¶
DataLabels(number_format: str | None = None, position: str | None = None, show_category: bool = False, show_series_name: bool = False)
Value labels drawn on the points or bars of a chart.
ErrorBars
dataclass
¶
ErrorBars(kind: str = 'fixed', value: float | None = None, direction: str = 'both', axis: str = 'y', end_cap: bool = True, color: str | None = None)
Error bars on a series.
kind is "fixed" (value units), "percentage" (value percent),
"std_dev" (value standard deviations) or "std_err" (no value).
direction picks "both", "plus" or "minus" bars; axis is
"y", or "x" on a scatter series.
Trendline
dataclass
¶
Trendline(type: str = 'linear', order: int | None = None, period: int | None = None, forward: float | None = None, backward: float | None = None, display_equation: bool = False, display_r_squared: bool = False, name: str | None = None, color: str | None = None)
A trendline fitted to a series.
order (2 to 6) is for "polynomial" and period (at least 2) for
"moving_average". forward and backward extend the line by that
many categories (X units on a scatter chart).
LoadedChart
dataclass
¶
LoadedChart(chart_type: str | None = None, title: str | None = None, series_count: int = 0, anchor: str | None = None, part: str | None = None, xml: bytes = b'')
A chart read back from a workbook, preserved as its original parts.
The title, the axis titles, the legend position and the titles and colours
of the series (set_series_title(), set_series_color()) can be
changed; the rest of the chart is saved as it was read. x_axis_title is
the title of the category (or X) axis and y_axis_title that of the
value axis; legend_position is None when the chart has no legend.
Setting None removes the title or the legend.
x_axis_title
property
writable
¶
x_axis_title: str | None
The title of the first axis (usually the category axis), or None.
y_axis_title
property
writable
¶
y_axis_title: str | None
The title of the second axis (usually the value axis), or None.
series_titles
property
¶
series_titles: list[str | None]
The literal title of each series (None when it reads a cell).
legend_position
property
writable
¶
legend_position: str | None
The legend position ("r", "b" and so on), or None without a legend.
set_series_title
¶
set_series_title(index: int, text: str) -> None
Give series index a literal title.
Source code in src/xlspy/charts.py
246 247 248 249 250 | |
set_series_color
¶
set_series_color(index: int, color: str) -> None
Fill series index (or draw its line) in color, a '#RRGGBB' string.
Source code in src/xlspy/charts.py
252 253 254 255 256 257 258 | |
PivotTable
dataclass
¶
PivotTable(source: ExcelTable | str, rows: str | tuple[str, ...], values: object, location: str = 'A3', columns: str | tuple[str, ...] = (), filters: str | tuple[str, ...] = (), sheet: str | None = None, name: str | None = None, style: str = 'PivotStyleLight16', data_caption: str = 'Values', autofit_columns: bool = False)
A compact pivot table over the table source.
source is an ExcelTable written by the same write_sheet call
(or its display name). location is the top-left cell of the pivot; it
may name the sheet ("Summary!A3") instead of using sheet. When
sheet is omitted the pivot is placed on the source sheet, below the
table. Otherwise the target sheet must be written after the source sheet,
or left empty and saved as is.
Examples:
Summarise a written table by region and quarter:
from xlspy import ExcelTable, PivotTable, PivotValue, XlsxWriter
rows = [
["Region", "Quarter", "Sales"],
["North", "Q1", 1300],
["South", "Q1", 1600],
["North", "Q2", 1400],
]
sales = ExcelTable("SalesTable", "A1:C4")
with XlsxWriter("pivot.xlsx") as workbook:
workbook.add_sheet("Data")
workbook.write_sheet(
rows,
tables=[sales],
pivots=[
PivotTable(
sales,
rows="Region",
columns="Quarter",
values=[PivotValue("Sales", "sum", number_format="#,##0")],
location="A3",
sheet="Summary",
)
],
)
workbook.add_sheet("Summary")
workbook.write_sheet([])
See Also
PivotValue for aggregations and number formats, and ExcelTable for
the source range.
PivotValue
dataclass
¶
PivotValue(field: str, function: str = 'sum', name: str | None = None, number_format: str | None = None)
One value field: field summarised with function.
name is the caption shown in the pivot (default: "Sum of Field").
number_format is an Excel format string applied to the rendered cells
and to the data field.
caption
property
¶
caption: str
The field caption: name, or the function and field, such as "Sum of Sales".
Formula
dataclass
¶
Formula(text: str, value: object = None, array_ref: str | None = None, spill_ref: str | None = None)
A formula cell.
text is the formula without its leading =. value is an optional
cached result, written so that readers that do not recalculate still see a
number. array_ref (for example "B2:B5") writes a legacy
array (CSE) formula over that range. spill_ref writes a dynamic-array
formula over the range: Excel stores the anchor as an array formula and the
file carries the dynamic-array cell metadata.
Examples:
Put a formula in a row, with an optional cached result:
from xlspy import Formula, XlsxWriter
rows = [
["A", "B", "Total"],
[2, 3, Formula("A2+B2", value=5)],
[4, 6, Formula("A3+B3")],
]
with XlsxWriter("formulas.xlsx") as workbook:
workbook.add_sheet("Data")
workbook.write_sheet(rows)
Formula text has no leading =. A plain string is always written as
text, so exported data cannot inject a formula.
See Also
Hyperlink for links, and the guide section on XLSB formula limits.
ArrayFormula
dataclass
¶
ArrayFormula(ref: str, text: str = '')
A legacy CSE array formula that fills ref.
The same object openpyxl's openpyxl.worksheet.formula.ArrayFormula
represents: Excel stores the formula once, in the top-left cell of the
range, and fills the other cells from it. text is the formula without
its leading =. Assign it to a cell to write an array formula:
from xlspy import ArrayFormula, Workbook
workbook = Workbook()
sheet = workbook.active
sheet["A1"] = 1
sheet["A2"] = 2
sheet["B1"] = ArrayFormula("B1:B2", "A1:A2*2")
workbook.save("array.xlsx")
A dynamic-array formula is written with Formula(..., spill_ref=...);
ArrayFormula is the static CSE form.
DataTableFormula
dataclass
¶
DataTableFormula(ref: str, ca: bool = False, dt2D: bool = False, dtr: bool = False, r1: str | None = None, r2: str | None = None, del1: bool = False, del2: bool = False)
A data-table formula (What-If Analysis > Data Table).
The fields follow openpyxl's DataTableFormula and the OOXML
<f t="dataTable"> attributes: r1/r2 are the input cells,
dt2D marks a two-dimensional table, dtr a row-oriented one, and
del1/del2 are Excel's "delete" flags. A data-table formula has no
text and no cached value of its own.
DefinedName
dataclass
¶
DefinedName(name: str, formula: str, scope: str | None = None, localSheetId: int | None = None, hidden: bool | None = None, comment: str | None = None)
A global name, or a local name scoped to a worksheet's title.
resolved
¶
resolved(sheets: Collection[str]) -> DefinedName
This name with scope and localSheetId both set for the sheets
in sheets (either one names the sheet). KeyError for a sheet that is
not there, ValueError when the two name different sheets.
Source code in src/xlspy/_metadata.py
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 | |
to_xml
¶
to_xml(sheets: Collection[str]) -> str
The <definedName> element.
sheets are the sheet names in order; a sheet scope becomes its position.
Source code in src/xlspy/_metadata.py
259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 | |
ExternalLink
dataclass
¶
ExternalLink(index: int, target: str | None, sheet_names: list[str] = list(), part: str | None = None)
A workbook that formulas refer to, as [index] in their text.
index counts from 1 as in the formulas, target is the path or URL
of the other workbook (None when the file does not say) and
sheet_names its sheets. Links are read, not edited; they are saved as
they were.
Comment
dataclass
¶
Comment(text: str, author: str, width: float = 144, height: float = 79)
A classic cell note. Width and height are pixels at 96 DPI.
Examples:
Notes are keyed by cell address in the comments sheet option:
from xlspy import Comment, XlsxWriter
with XlsxWriter("notes.xlsx") as workbook:
workbook.add_sheet("Data")
workbook.write_sheet(
[["Amount"], [1200]],
comments={"A2": Comment("Confirm this amount", "Jan", 240, 100)},
)
The author is required and is shown in Excel's note header.
See Also
XlsxUpdater.set_comments for notes on an existing workbook.
Hyperlink
dataclass
¶
Hyperlink(target: str, text: str | None = None, tooltip: str | None = None)
A link written as the value of a cell.
target is an http, https, mailto or ftp URL, or an
internal location written as "#Sheet Name!B2" (quote the sheet name
with single quotes when it contains spaces: "#'Sales Data'!B2"). Other
schemes and relative file paths are refused. text is the displayed
label and defaults to the target; tooltip is shown on hover. Linked
cells use the built-in hyperlink look unless the cell has its own style.
Examples:
A Hyperlink is a cell value, so it goes where the text belongs:
from xlspy import Hyperlink, XlsxWriter
rows = [
["Report", Hyperlink("https://example.com/report", text="Open report")],
["Back", Hyperlink("#Links!A1", text="Back to top")],
]
with XlsxWriter("links.xlsx") as workbook:
workbook.add_sheet("Links")
workbook.write_sheet(rows)
See Also
Comment for a note attached to a cell, and Shape for a linked
shape.
Image
dataclass
¶
Image(path: str | PathLike | bytes | bytearray | memoryview | BinaryIO, anchor: str = 'A1', width: int | None = None, height: int | None = None, description: str | None = None, data: bytes = b'', extension: str = '', pixel_width: int = 0, pixel_height: int = 0)
A PNG, JPEG, GIF or BMP picture anchored to a cell.
path is a file path, the image bytes (bytes, bytearray or
memoryview), or a binary file object such as io.BytesIO, which
is read from its current position. width and height are in pixels. When only one is given the other
keeps the image's aspect ratio; when neither is given the image's own size
is used. description is the alternative text.
Shape
dataclass
¶
Shape(anchor: str, width: int = 200, height: int = 80, kind: str = 'rect', text: str | None = None, fill: str | None = None, line: str | None = None, font_size: float = 11, font_color: str = '#000000', bold: bool = False, align: str = 'left', valign: str = 'top', link_cell: str | None = None, name: str | None = None)
A rectangle, rounded rectangle, ellipse or text box over the sheet.
anchor is the top-left cell, width and height are in pixels.
fill and line are #RRGGBB colours, or None for no fill or
no outline. text may hold several lines separated by "\n".
Examples:
A titled card above a table:
from xlspy import Shape, XlsxWriter
with XlsxWriter("shapes.xlsx") as workbook:
workbook.add_sheet("Dashboard")
workbook.write_sheet(
[["Region", "Sales"], ["North", 120], ["South", 90]],
shapes=[
Shape("A4", width=240, height=60, kind="round",
text="Sales overview", fill="#183C52",
font_color="#FFFFFF", bold=True, valign="center")
],
)
kind is "rect", "round", "ellipse" or "textbox".
Set link_cell to make the shape navigate to a cell.
See Also
Image for a picture and Chart for a chart anchored the same way.
Slicer
dataclass
¶
Slicer(table: str, column: str, anchor: str = 'H2', width: int = 144, height: int = 180, caption: str | None = None, name: str | None = None, columns: int = 1)
A slicer filtering the table table by its column column.
table is the display name of an ExcelTable written to the same
sheet in the same call, and column the header text of one of its
columns. name (default: the column) and caption (default: the
column) must be unique within the workbook for name.
Examples:
A Region slicer beside a table on the same sheet:
from xlspy import ExcelTable, Slicer, XlsxWriter
rows = [["Region", "Sales"], ["North", 120], ["South", 90], ["East", 75]]
with XlsxWriter("slicer.xlsx") as workbook:
workbook.add_sheet("Data")
workbook.write_sheet(
rows,
tables=[ExcelTable("SalesTable", "A1:B4")],
slicers=[Slicer("SalesTable", "Region", anchor="D2",
width=160, height=200, caption="Region")],
)
The slicer drives the table's filter; Excel shows it when the file opens. The table and slicer must be written by the same call.
See Also
ExcelTable for the source range, and PivotTable for aggregation.
SparklineGroup
dataclass
¶
SparklineGroup(data: str, location: str, kind: str = 'line', color: str = _DEFAULT_COLOR, negative_color: str = _POINT_COLOR, axis_color: str = '#000000', marker_color: str = _POINT_COLOR, high_color: str = _POINT_COLOR, low_color: str = _POINT_COLOR, first_color: str = _POINT_COLOR, last_color: str = _POINT_COLOR, line_width: float = _DEFAULT_LINE_WIDTH, markers: bool = False, high_point: bool = False, low_point: bool = False, first_point: bool = False, last_point: bool = False, negative_points: bool = False, empty_cells: str = 'gap', show_hidden: bool = False, show_axis: bool = False, right_to_left: bool = False, axis_min: float | str | None = None, axis_max: float | str | None = None)
One style of sparklines over data, shown in location.
Examples:
A line sparkline beside each row of a small table:
from xlspy import SparklineGroup, XlsxWriter
rows = [["Month", "Sales", "Trend"],
["Jan", 12, None], ["Feb", 15, None], ["Mar", 11, None]]
with XlsxWriter("sparklines.xlsx") as workbook:
workbook.add_sheet("Data")
workbook.write_sheet(
rows,
sparklines=[SparklineGroup("B2:B4", "C2:C4", kind="line",
markers=True, last_point=True)],
)
kind is "line", "column" or "win_loss". The group is
written to the sheet in the same write_sheet call.
See Also
Chart for a full chart, and DataLabels for chart point labels.
DataValidation
dataclass
¶
DataValidation(type: str, sqref: str | tuple[str, ...] | list[str], formula1: object = None, formula2: object = None, operator: str | None = None, allow_blank: bool = True, show_dropdown: bool = True, show_input_message: bool = False, prompt_title: str | None = None, prompt: str | None = None, show_error_message: bool = True, error_title: str | None = None, error: str | None = None, error_style: str = 'stop', ime_mode: str | None = None)
A validation rule applied to one or more cell ranges.
type is one of list, whole, decimal, date, time,
text_length or custom. For list the formula1 is either a
literal list such as '"New,Active,Closed"' or a range such as
"Lists!$A$2:$A$9". For custom it is a formula that must evaluate to
true for valid input. operator applies to the numeric, date, time and
text-length types only, and defaults to between.
show_dropdown=False hides the arrow of a list rule. allow_blank
accepts empty cells. Prompts and error messages are shown when their
show_* flag is true.
Examples:
Add a dropdown, a numeric range and a date rule to one sheet:
import datetime
from xlspy import DataValidation, XlsxWriter
rows = [["Region", "Amount", "Date"], ["North", 10, datetime.date(2026, 1, 5)]]
with XlsxWriter("validated.xlsx") as workbook:
workbook.add_sheet("Data")
workbook.write_sheet(
rows,
data_validations=[
DataValidation("list", "A2:A50", formula1='"North,South,East"'),
DataValidation("whole", "B2:B50", formula1=1, formula2=100),
DataValidation("date", "C2:C50", formula1=datetime.date(2026, 1, 1),
operator="greater_than"),
],
)
Invalid combinations raise ValueError when the rule is created.
See Also
Formula for custom rules, and ExcelTable for structured
references in a validation formula.
showDropDown
property
¶
showDropDown: bool
openpyxl's raw OOXML flag: True hides the in-cell list.
It is the inverse of show_dropdown.
IgnoredError
dataclass
¶
IgnoredError(sqref: str, evalError: bool | None = None, twoDigitTextYear: bool | None = None, numberStoredAsText: bool | None = None, formula: bool | None = None, formulaRange: bool | None = None, unlockedFormula: bool | None = None, emptyCellReference: bool | None = None, listDataValidation: bool | None = None, calculatedColumn: bool | None = None)
Error checks switched off for sqref (space-separated ranges).
Each flag names a check: numberStoredAsText for "number stored as
text", formula for "inconsistent formula", formulaRange for
"formula omits adjacent cells", unlockedFormula, evalError,
twoDigitTextYear, emptyCellReference, listDataValidation and
calculatedColumn.
Group
dataclass
¶
Group(first: int | str, last: int | str, collapsed: bool = False)
Rows or columns from first to last, both inclusive and zero-based.
Columns may also be given as letters, such as Group("D", "F").
collapsed hides the group and sets the collapsed flag on the summary
row or column just after last.
Examples:
Collapse rows 2-10 behind a summary row 11:
from xlspy import Group, Style, XlsxWriter
with XlsxWriter("grouped.xlsx") as workbook:
workbook.add_sheet("Data")
workbook.write_sheet(
[["Item", "Value"], *[[f"item-{i}", i] for i in range(10)],
["Total", 45]],
row_groups=[Group(2, 10, collapsed=True)],
header_style=Style(bold=True),
)
Use column_groups=[Group("B", "D")] for the same effect across
columns; letters and zero-based indexes are both accepted.
See Also
row_heights and hidden_rows for related row options of
write_sheet.
PrintSettings
dataclass
¶
PrintSettings(orientation: str | None = None, paper_size: str | int | None = None, margins: PageMargins | None = None, print_area: str | None = None, repeat_rows: str | None = None, repeat_columns: str | None = None, fit_to_width: int | None = None, fit_to_height: int | None = None, scale: int | None = None, center_horizontally: bool = False, center_vertically: bool = False, header: str | None = None, footer: str | None = None, row_breaks: tuple[int, ...] | list[int] | None = None, col_breaks: tuple[int, ...] | list[int] | None = None)
Print layout for one worksheet.
fit_to_width and fit_to_height switch the sheet to fit-to-page
scaling; fit_to_height=0 lets the page count follow the content.
Otherwise scale (10-400 percent) applies. header and footer
are raw Excel header codes such as "&LReport&RPage &P of &N"; write
a literal ampersand as &&. row_breaks and col_breaks name the
row or column after which a manual page break is placed (1-based).
Examples:
Landscape A4 with a repeating header and a footer:
from xlspy import PageMargins, PrintSettings, XlsxWriter
with XlsxWriter("print.xlsx") as workbook:
workbook.add_sheet("Report")
workbook.write_sheet(
[["Region", "Sales"], ["North", 120], ["South", 90]],
freeze_panes="A2",
print_settings=PrintSettings(
orientation="landscape",
paper_size="A4",
print_area="A1:B50",
repeat_rows="1:1",
fit_to_width=1,
margins=PageMargins(left=0.4, right=0.4),
footer="&LReport&RPage &P of &N",
),
)
See Also
PageMargins for the inch-based margins.
fit_to_page
property
¶
fit_to_page: bool
True when a page count to fit the width or height to is set.
PageMargins
dataclass
¶
PageMargins(left: float = 0.7, right: float = 0.7, top: float = 0.75, bottom: float = 0.75, header: float = 0.3, footer: float = 0.3)
Page margins in inches. Defaults match the historical xlspy layout.
SheetProtection
dataclass
¶
SheetProtection(enabled: bool = True, select_locked_cells: bool = True, select_unlocked_cells: bool = True, password: str | None = None, hashed_password: str | None = None)
Enable sheet protection. Selection flags mean 'allow selection'.
password_hash
property
¶
password_hash: str | None
The legacy hash of the password (or the hash given directly), or None.
to_xml
¶
to_xml() -> str
The <sheetProtection> element, or an empty string when protection is off.
Source code in src/xlspy/_metadata.py
327 328 329 330 331 332 333 334 335 336 | |
WorkbookProtection
dataclass
¶
WorkbookProtection(lock_structure: bool = True, password: str | None = None)
Protect workbook structure; this does not encrypt workbook data.
to_xml
¶
to_xml() -> str
The <workbookProtection> element, or an empty string when the structure
is not locked.
Source code in src/xlspy/_metadata.py
349 350 351 352 353 354 355 356 | |