API reference

Everything below is importable from the top-level unifyxl package.

Opening and creating workbooks

unifyxl.load_workbook(source, *, data_only=False)[source]

Load an xlsx, xlsm, or xls workbook detected by its contents.

No formula calculation is performed. The xlsx backend preserves features supported by openpyxl, including embedded VBA when present. The xls backend loads the common model into memory; features outside that model are lost when saving, including charts, images, comments, and data validation.

Parameters:
  • source (str | PathLike | IO[bytes]) – A filesystem path or seekable binary stream containing the workbook at its current position. A supplied stream remains open, but loading consumes its contents.

  • data_only (bool) – For xlsx, return cached formula results instead of formula strings. Defaults to False. Ignored for xls, which always reads cached results because xlrd cannot read formulas.

Returns:

A format-specific implementation of Workbook.

Raises:
Return type:

Workbook

Example

Read the active sheet’s values:

wb = load_workbook("report.xlsx", data_only=True)
rows = wb.active.values()
unifyxl.new_workbook(format='xlsx', *, _empty=False)[source]

Create a workbook with one worksheet named "Sheet" by default.

Parameters:
  • format (str) – Output model, either "xlsx" (the default) or "xls".

  • _empty (bool) – Internal conversion option. If True, create no worksheets; at least one worksheet must be added before saving. Defaults to False.

Returns:

A new format-specific Workbook with no associated source path.

Raises:

ValueError – format is neither "xlsx" nor "xls".

Return type:

Workbook

unifyxl.detect_format(source)[source]

Detect an Excel container format from its contents.

ZIP and OLE2 signatures identify xlsx and xls containers, respectively; this does not validate the workbook inside the container. A stream’s position is restored after reading the signature.

Parameters:

source (str | PathLike | IO[bytes]) – A filesystem path or a seekable binary stream. Streams are inspected at their current position and remain open.

Returns:

The string "xlsx" or "xls". An xlsm container returns "xlsx".

Raises:
  • UnsupportedFormatError – The signature matches neither supported format.

  • OSError – The path cannot be opened or the source cannot be read or sought.

Return type:

str

Workbooks, worksheets and cells

class unifyxl.Workbook[source]

Abstract workbook API shared by xlsx and xls implementations.

Create instances with unifyxl.new_workbook() or unifyxl.load_workbook(). Iterate to visit worksheets in tab order, index by a case-sensitive sheet name or 0-based position, and use del with the same keys to remove sheets. Rows and columns within sheets are 1-based.

format

Backend format, either "xlsx" or "xls".

Type:

str

path

Original source path when loaded from a filesystem path, otherwise None. Saving does not update this attribute.

Type:

str | None

abstract property worksheets: list[Worksheet]

Read-only property returning worksheets in tab order.

The list is a snapshot. Use create_sheet and remove_sheet to change the workbook’s sheets.

Type:

list[Worksheet]

property sheetnames: list[str]

Read-only snapshot of worksheet titles in tab order.

Type:

list[str]

property active: Worksheet

Sheet selected when opened in Excel; settable.

Assign a worksheet belonging to this workbook or a nonnegative 0-based sheet index. Negative indexes are rejected by this setter.

Raises:
  • IndexError – The workbook is empty when read, or the assigned integer index is outside 0..len(workbook)-1.

  • ValueError – An assigned worksheet does not belong to this workbook.

Type:

Worksheet

create_sheet(title=None, index=None)[source]

Create a worksheet and insert it at a 0-based tab position.

Parameters:
  • title (str | None) – Nonempty name of at most 31 characters, unique ignoring case. []:*?/, backslashes, and leading or trailing apostrophes are forbidden. None chooses an unused SheetN name (compared ignoring case), starting with the current sheet count plus one.

  • index (int | None) – 0-based insertion position, with Python list insertion semantics for negative and out-of-range positions. None appends the sheet.

Returns:

The newly created Worksheet.

Raises:
  • ValueError – The supplied title is invalid or duplicates an existing name.

  • TypeError – The insertion index cannot be used as a list index.

Return type:

Worksheet

remove_sheet(ws)[source]

Remove a worksheet and keep the active selection consistent.

If the active sheet is removed, a neighboring sheet is selected when one remains. Removing the final sheet is allowed, but saving then fails until a sheet is added.

Parameters:

ws (Worksheet) – Worksheet belonging to this workbook.

Raises:

ValueError – The worksheet does not belong to this workbook.

property theme_colors: tuple[str, ...]

Read-only 12 resolved theme RGB strings.

The order follows the 0-based slots in THEME_COLOR_NAMES. New workbooks and workbooks loaded from xls use the Office default theme. An in-memory xls workbook converted from xlsx can retain the source theme for subsequent conversion; saving to xls cannot store that theme.

Type:

tuple[str, …]

theme_color(index, tint=0.0)[source]

Resolve a theme color against this workbook’s theme.

Xlsx saves the resulting theme reference so it follows theme changes in Excel. Xls saves only its RGB palette representation.

Parameters:
  • index (int) – 0-based integer theme slot in 0..11, following THEME_COLOR_NAMES. Booleans are rejected.

  • tint (float) – Number in -1.0..1.0, defaulting to 0.0. Negative values darken; positive values lighten. Booleans are rejected.

Returns:

A Color with resolved RGB, theme slot, and tint.

Raises:

ValueError – The theme index or tint is invalid.

Return type:

Color

save(target, format=None)[source]

Save to a path or binary stream, converting formats if needed.

Format selection uses a truthy format argument first, then a recognized path extension (.xls, .xlsx, or .xlsm), then self.format. A stream has no inferred extension. Conversion writes a separate common model and leaves this workbook’s format and source path unchanged.

The xls writer supports 65,536 rows, 256 columns, and 4,000 distinct cell formats after output normalization. Its 56-color palette approximates excess colors with a warning, and indentation is clipped to 15. Only the common model is preserved during conversion or xls load/save; charts, images, comments, and other unsupported features are not carried over. Formula results are not calculated or refreshed.

Parameters:
  • target (str | PathLike | IO[bytes]) – Destination filesystem path or writable binary stream. A path may overwrite an existing file; supplied streams remain open.

  • format (str | None) – Optional "xlsx" or "xls" override. None uses the extension or current format as described above.

Raises:
  • ValueError – The selected format is unknown, there are no worksheets, or xlwt cannot parse an xls formula. Backend validation errors also propagate.

  • FormatLimitError – Conversion exceeds xls row or column limits, or the xls output exceeds 4,000 distinct cell formats.

  • OSError – The destination cannot be opened or written.

convert(format)[source]

Copy the workbook through the common model into a requested format.

Copies values, modeled styles, merged ranges and their styles, column widths, row heights, freeze panes, and the active sheet. Theme information and palette entries are carried in memory, though xls files cannot store themes. Features outside the common API, such as charts and images, are not copied, even if the requested format matches the current format.

Xls palette mapping, font-size rounding, indentation clipping, and the 4,000-format limit are applied later when saving. Formula strings are copied where available; cached xls results cannot recover the formulas.

Parameters:

format (str) – Destination model, either "xlsx" or "xls".

Returns:

A separate Workbook with no associated source path, even when converting to the current format. The original is unchanged.

Raises:
  • ValueError – The format is unknown, or copied sheet names or dimensions fail destination validation.

  • FormatLimitError – A copied cell, merge, dimension, or freeze pane exceeds the xls limits of 65,536 rows or 256 columns.

Return type:

Workbook

class unifyxl.Worksheet(workbook)[source]

Abstract worksheet API with 1-based row and column coordinates.

Obtain worksheets from a Workbook. Both backends support cell values, shared style parts, rectangular merges, dimensions, and freeze panes. Xlsx supports 1,048,576 rows and 16,384 columns; xls writes are limited to 65,536 rows and 256 columns. Reading an empty xls coordinate within xlsx bounds does not itself enforce the smaller xls limits.

Parameters:

workbook (Workbook) – Owning workbook, retained by the worksheet.

property workbook: Workbook

Read-only workbook that owns this worksheet.

Type:

Workbook

property title: str

Worksheet name; settable to rename the worksheet.

Assigning the current title is a no-op. Names must be nonempty, at most 31 characters, unique within the workbook ignoring case, and free of []:*?/ and backslashes. A name cannot start or end with an apostrophe.

Raises:

ValueError – The new title violates a naming rule.

Type:

str

abstract property merged_ranges: list[CellRange]

Read-only property returning sorted merged ranges.

The returned list is a snapshot; change merges with merge_cells or unmerge_cells.

Type:

list[CellRange]

abstractmethod get_column_width(col)[source]

Read an explicit column width in Excel character units.

Parameters:

col (int | str) – 1-based column index or case-insensitive letters in A through XFD.

Returns:

The explicit width, or None to use the sheet/application default. For xlsx this also recognizes widths shared by a grouped column span.

Raises:

ValueError – The column is invalid or outside xlsx bounds.

Return type:

float | None

abstractmethod set_column_width(col, width)[source]

Set one column’s width or reset it to the default.

Parameters:
  • col (int | str) – 1-based column index or case-insensitive column letters.

  • width (float | None) – Width in Excel character units, greater than 0 and at most 255. None removes the explicit width. Xls stores widths rounded to 1/256 character when saved.

Raises:
  • ValueError – The column is invalid or the width is outside (0, 255].

  • FormatLimitError – The column exceeds the xls limit of 256.

abstractmethod get_row_height(row)[source]

Read an explicit row height in points.

Parameters:

row (int) – 1-based integer row index within xlsx bounds.

Returns:

The explicit height, or None to use the sheet/application default.

Raises:

ValueError – The row is invalid or outside 1..1048576.

Return type:

float | None

abstractmethod set_row_height(row, height)[source]

Set one row’s height or reset it to the default.

Parameters:
  • row (int) – 1-based integer row index.

  • height (float | None) – Height in points, greater than 0 and at most 409. None removes the explicit height. Xls stores heights rounded to 1/20 point when saved.

Raises:
  • ValueError – The row is invalid or the height is outside (0, 409].

  • FormatLimitError – The row exceeds the xls limit of 65,536.

property freeze_panes: str | None

Top-left scrollable cell, such as "B2"; settable.

Rows above and columns to the left are frozen. Setting an A1 reference normalizes its case and removes dollar signs. Setting None or "A1" unfreezes all panes.

Raises:
  • ValueError – The assigned reference is invalid or outside xlsx bounds.

  • FormatLimitError – The reference exceeds xls row or column limits.

Type:

str | None

property shapes: tuple[Shape, ...]

Shapes on the sheet, back to front (xlsx only).

Includes text boxes, connectors, groups, pictures and charts. Members of a group are available from the group’s own shapes. Pictures and charts added through openpyxl appear after saving and loading.

Raises:

UnsupportedFeatureError – The workbook is an xls workbook.

Type:

tuple[Shape, …]

add_shape(anchor, geometry='rect', *, text='', fill=None, line=None, name=None)[source]

Add a shape in front of the others (xlsx only).

Parameters:
Returns:

A handle to the new shape.

Raises:
Return type:

Shape

add_text_box(anchor, text='', *, fill=None, line=None, name=None)[source]

Add a text box in front of the other shapes (xlsx only).

Parameters:
Returns:

A handle to the new text box.

Raises:
Return type:

Shape

add_connector(anchor, geometry='line', *, flip_horizontal=False, flip_vertical=False, line=None, name=None)[source]

Add a line or connector in front of the other shapes (xlsx only).

It runs from the top left to the bottom right of the anchor unless it is flipped, and is not attached to other shapes.

Parameters:
Returns:

A handle to the new connector.

Raises:
Return type:

Shape

remove_shape(shape)[source]

Remove a shape, picture, chart, connector or group (xlsx only).

Parameters:

shape (Shape) – A handle obtained from this sheet, or from one of its groups.

Raises:
property max_row: int

Read-only largest row containing a value, style, or merged range.

Returns 0 for an empty sheet. Custom row heights alone do not extend it.

Type:

int

property max_column: int

Read-only largest column with a value, style, or merged range.

Returns 0 for an empty sheet. Custom column widths alone do not extend it.

Type:

int

cell(row, column, value=<object object>)[source]

Get a cell handle and optionally assign a value.

Parameters:
  • row (int) – 1-based integer row index within xlsx bounds.

  • column (int | str) – 1-based integer column index or case-insensitive column letters within xlsx bounds.

  • value (Any) – Optional initial value, following Cell.value. Omitting this argument leaves the cell unchanged; explicitly passing None clears its value.

Returns:

A live Cell handle. Reading a handle alone does not store a cell.

Raises:
  • ValueError – A coordinate is invalid, or the value is a non-finite float.

  • TypeError – The supplied value has an unsupported type.

  • MergedCellError – A value is supplied for a non-anchor merged cell.

  • FormatLimitError – An assigned string exceeds 32,767 characters, or an xls write exceeds 65,536 rows or 256 columns.

Return type:

Cell

iter_rows(min_row=1, max_row=None, min_col=1, max_col=None, values_only=False)[source]

Iterate over an inclusive rectangular area in row order.

Parameters:
  • min_row (int) – First 1-based row, defaulting to 1.

  • max_row (int | None) – Last 1-based row. Defaults to self.max_row when None.

  • min_col (int) – First 1-based integer column, defaulting to 1.

  • max_col (int | None) – Last 1-based integer column. Defaults to self.max_column when None.

  • values_only (bool) – If True, yield values instead of cell handles. Defaults to False.

Yields:

A tuple of cells or values for each row. Empty cells have value None. A reversed row interval yields no rows; a reversed column interval yields empty tuples. An empty sheet with default bounds yields no rows.

Raises:

ValueError – A minimum index is invalid, or a maximum index at or above its minimum is outside xlsx bounds. Validation occurs on iteration.

Return type:

Iterator[tuple[Any, …]]

values()[source]

Collect the used rectangle’s values as a two-dimensional list.

Returns:

A list of rows, each a list of values starting at A1 and extending through max_row and max_column. Empty cells contain None; an empty sheet returns [].

Return type:

list[list[str | int | float | bool | datetime | date | time | timedelta | None]]

append(values)[source]

Write values into the row after the current last used row.

None entries are skipped. Existing styled cells and merged ranges contribute to the last used row. Writes are sequential; an error can leave an earlier part of the row written.

Parameters:

values (list[Any] | tuple[Any, ...]) – List or tuple of cell values starting in column 1 (A).

Raises:
  • ValueError – A written coordinate exceeds xlsx bounds or a value is a non-finite float.

  • TypeError – A value has an unsupported type.

  • FormatLimitError – A string exceeds 32,767 characters, or an xls write exceeds 65,536 rows or 256 columns.

merged_range_at(row, col)[source]

Find the merged range containing a coordinate.

Parameters:
  • row (int) – 1-based row index. This lookup does not validate sheet bounds.

  • col (int) – 1-based column index. This lookup does not validate sheet bounds.

Returns:

The containing CellRange, or None when no merged range matches.

Return type:

CellRange | None

merge_cells(ref)[source]

Merge an inclusive rectangle, keeping the top-left value.

Other cells’ values and formatting are reset. The anchor can acquire missing right and bottom borders from the bottom-right cell; its edge borders are propagated along the merged boundary in both backends.

Parameters:

ref (str | CellRange) – A range reference such as "A1:C2", or a CellRange.

Returns:

The normalized merged CellRange.

Raises:
  • ValueError – The reference is invalid, covers one cell, or overlaps an existing merge, including an identical existing merge.

  • FormatLimitError – The range exceeds 65,536 rows or 256 columns in xls.

Return type:

CellRange

unmerge_cells(ref)[source]

Unmerge an exact existing range, keeping the top-left cell.

Values cleared during merging are not restored. Non-anchor cells and their formatting are removed.

Parameters:

ref (str | CellRange) – A range reference or CellRange matching a complete merge.

Raises:

ValueError – The reference is invalid or is not an exact merged range.

class unifyxl.Cell(ws, row, column)[source]

A lightweight handle that reads and writes a worksheet cell.

The handle stores coordinates rather than a copy of the cell’s contents. Use Worksheet.cell() or worksheet indexing to obtain handles. Row and column validation uses xlsx bounds; xls checks its smaller bounds on writes.

Parameters:
  • ws (Worksheet) – Worksheet containing the cell.

  • row (int) – 1-based integer row in 1..1048576.

  • column (int) – 1-based integer column in 1..16384.

row

1-based row index supplied at construction.

Type:

int

column

1-based column index supplied at construction.

Type:

int

Raises:

ValueError – A coordinate is invalid, including a boolean index.

property worksheet: Worksheet

Read-only worksheet containing this cell.

Type:

Worksheet

property coordinate: str

Read-only uppercase A1 reference, such as "B2".

Type:

str

property value: str | int | float | bool | datetime | date | time | timedelta | None

Cell contents; settable to write or clear the cell.

Values may be strings, integers, finite floats, booleans, datetime, date, time, timedelta, or None for an empty cell. Assigning a Decimal converts it to float. A string beginning with = and containing more than one character becomes a formula; standard Excel error strings such as "#N/A" become error cells. Formulas are never calculated. Date/time assignment may set a suitable number format automatically.

Loaded xls formulas expose cached results. For xlsx, data_only controls whether loading exposes formula strings or cached results.

Raises:
  • MergedCellError – Setting a non-anchor cell of a merged range, even to None. Only the top-left cell may hold a value.

  • FormatLimitError – A string exceeds 32,767 characters in either format, or an xls write exceeds 65,536 rows or 256 columns.

  • ValueError – A floating-point value is not finite.

  • TypeError – The assigned value has an unsupported type.

Type:

CellValue

property style: CellStyle

Complete common formatting; settable to replace it.

Use cell.style.replace(...) to derive a modified immutable style. For xlsx, assigning the complete style replaces all modeled parts and may lose details those parts cannot represent. Assigning an individual part, such as font, preserves unrelated openpyxl formatting.

Raises:
Type:

CellStyle

property font: Font

Font settings; settable to replace only the font.

Use cell.font = cell.font.replace(bold=True) to change one field.

Raises:
Type:

Font

property fill: Fill

Pattern fill; settable to replace only the fill.

Raises:
Type:

Fill

property border: Border

Four edge borders; settable to replace only the border.

Raises:
Type:

Border

property alignment: Alignment

Text layout; settable to replace only the alignment.

Raises:
Type:

Alignment

property number_format: str

Excel number format code; settable to replace only that code.

Raises:
Type:

str

property bg_color: Color | None

Visible solid-fill color; settable as a shortcut.

Returns None for a non-solid fill or automatic solid-fill color. Assigning a ColorLike value replaces the fill with Fill.solid(value). Assigning None removes the fill entirely.

Raises:
  • ValueError – The assigned color value is invalid.

  • TypeError – The assigned color has an unsupported type.

  • FormatLimitError – An xls write exceeds its row or column limit.

Type:

Color | None

property merged_range: CellRange | None

Read-only merged range containing this cell.

Returns None when the cell is outside all merged ranges.

Type:

CellRange | None

property is_merged: bool

Read-only flag for membership in a merged range.

The top-left anchor of a merged range also returns True.

Type:

bool

property is_formula: bool

Read-only flag indicating a stored formula.

Formula values are strings beginning with =. Formulas loaded from xls always return False because xlrd reads only cached results; newly assigned xls formulas return True. Xlsx loaded with data_only=True also exposes cached results rather than formulas.

Type:

bool

Styles

class unifyxl.CellStyle(font=<factory>, fill=<factory>, border=<factory>, alignment=<factory>, number_format='General')[source]

Immutable formatting supported by both workbook backends.

Use replace(**changes) to create a modified copy. Nested style parts are immutable too, so update them with their own replace() methods.

font

Font settings. Defaults to Font() with the workbook’s default name and size and otherwise unadorned text.

Type:

Font

fill

Pattern fill. Defaults to Fill() with no fill.

Type:

Fill

border

Four edge borders. Defaults to Border() with no lines.

Type:

Border

alignment

Text layout. Defaults to Alignment() with general horizontal alignment and bottom vertical alignment.

Type:

Alignment

number_format

Excel number format code. Defaults to "General". The code affects display and date/time interpretation.

Type:

str

without_theme()[source]

Replace theme colors throughout the style with their resolved RGB.

This is useful when comparing styles before and after saving through xls, which cannot retain theme metadata. Palette approximation can still change the visible colors in xls.

Returns:

A new CellStyle with plain RGB font, fill, and border colors. Other fields are unchanged.

Return type:

CellStyle

class unifyxl.Font(name=None, size=None, bold=False, italic=False, underline=None, strike=False, color=None, vert_align=None)[source]

Immutable font settings, with workbook defaults for name and size.

Use replace(**changes) to create a modified copy. Color inputs are normalized by normalize_color(). The xls writer rounds size to increments of 1/20 point.

name

Typeface name. Defaults to None to use the workbook’s default font name.

Type:

str | None

size

Font size in points, converted to float when provided. Defaults to None to use the workbook’s default size.

Type:

float | None

bold

Whether to use bold text. Defaults to False.

Type:

bool

italic

Whether to use italic text. Defaults to False.

Type:

bool

underline

None, "single", "double", "singleAccounting", or "doubleAccounting". Defaults to None for no underline; see UnderlineStyle.

Type:

UnderlineStyle | None

strike

Whether to strike through text. Defaults to False.

Type:

bool

color

Text color, accepting ColorLike inputs during construction. Defaults to None for automatic color.

Type:

Color | None

vert_align

None, "superscript", or "subscript". Defaults to None for normal text.

Type:

VertAlign | None

Raises:
  • ValueError – Underline, vertical alignment, color, or size conversion is invalid.

  • TypeError – A color type or size conversion is unsupported.

class unifyxl.Fill(pattern=None, fg_color=None, bg_color=None)[source]

An immutable pattern fill with foreground and background colors.

Use replace(**changes) to create a modified copy. For a solid cell background, use Fill.solid("FFFF00"); its visible color is fg_color.

pattern

A FillPattern member, including "solid", gray patterns, and directional patterns. Defaults to None for no fill.

Type:

FillPattern | None

fg_color

Foreground or solid-fill color, accepting ColorLike inputs. Defaults to None for automatic color.

Type:

Color | None

bg_color

Background color of a pattern, accepting ColorLike inputs. Defaults to None for automatic color. For a solid fill the visible color comes from fg_color instead.

Type:

Color | None

Raises:
  • ValueError – The pattern or a color value is invalid.

  • TypeError – A color has an unsupported type.

classmethod solid(color)[source]

Create a solid fill with the given visible background color.

Parameters:

color (Color | str | tuple[int, int, int]) – A ColorLike input accepted by normalize_color().

Returns:

A fill with pattern="solid", normalized fg_color, and no explicit pattern background color.

Raises:
Return type:

Fill

property background_color: Color | None

Read-only visible color for a solid fill.

Returns None for other patterns or a solid fill with automatic color.

Type:

Color | None

class unifyxl.Border(left=<factory>, right=<factory>, top=<factory>, bottom=<factory>)[source]

Immutable left, right, top, and bottom borders of a cell.

Use replace(**changes) to create a modified copy, or all() for matching edges. Diagonal and internal borders are outside this model.

left

Left edge. Defaults to Side() with no line.

Type:

Side

right

Right edge. Defaults to Side() with no line.

Type:

Side

top

Top edge. Defaults to Side() with no line.

Type:

Side

bottom

Bottom edge. Defaults to Side() with no line.

Type:

Side

classmethod all(style=BorderStyle.THIN, color=None)[source]

Create a box border with the same line on all four edges.

Parameters:
Returns:

A Border whose four edges share the same immutable Side.

Raises:
  • ValueError – The line style or color value is invalid.

  • TypeError – The color has an unsupported type.

Return type:

Border

class unifyxl.Side(style=None, color=None)[source]

An immutable line style and color for one border edge.

Use replace(**changes) to create a modified copy.

style

A BorderStyle member, such as BorderStyle.THIN, "medium", "dashed", or "double". Defaults to None for no line.

Type:

BorderStyle | None

color

Line color, accepting ColorLike inputs. Defaults to None for automatic color.

Type:

Color | None

Raises:
  • ValueError – The line style or color value is invalid.

  • TypeError – The color has an unsupported type.

class unifyxl.Alignment(horizontal=HorizontalAlignment.GENERAL, vertical=VerticalAlignment.BOTTOM, wrap_text=False, shrink_to_fit=False, indent=0, text_rotation=0)[source]

Immutable text alignment and layout settings.

Use replace(**changes) to create a modified copy.

horizontal

A HorizontalAlignment member: "general", "left", "center", "right", "fill", "justify", "centerContinuous", or "distributed". Defaults to "general".

Type:

HorizontalAlignment

vertical

A VerticalAlignment member: "top", "center", "bottom", "justify", or "distributed". Defaults to "bottom".

Type:

VerticalAlignment

wrap_text

Whether text wraps within the cell. Defaults to False.

Type:

bool

shrink_to_fit

Whether text shrinks to fit the cell. Defaults to False.

Type:

bool

indent

Indent level in 0..255, defaulting to 0. Saving to xls clips this to 15.

Type:

int

text_rotation

Excel rotation code, defaulting to 0. Codes 0..90 mean counterclockwise degrees; 91..180 mean 1 through 90 clockwise degrees; 255 stacks text vertically.

Type:

int

Raises:

ValueError – An alignment choice, indent, or rotation is out of range.

Style names

Style names are StrEnum members whose values are the OOXML / openpyxl names, so BorderStyle.THIN == "thin". Style constructors also accept the plain strings and convert them; values read from cells are always members. Type checkers accept only the members.

class unifyxl.FillPattern(*values)[source]

Fill pattern of a Fill; None means no fill.

SOLID = 'solid'
MEDIUM_GRAY = 'mediumGray'
DARK_GRAY = 'darkGray'
LIGHT_GRAY = 'lightGray'
DARK_HORIZONTAL = 'darkHorizontal'
DARK_VERTICAL = 'darkVertical'
DARK_DOWN = 'darkDown'
DARK_UP = 'darkUp'
DARK_GRID = 'darkGrid'
DARK_TRELLIS = 'darkTrellis'
LIGHT_HORIZONTAL = 'lightHorizontal'
LIGHT_VERTICAL = 'lightVertical'
LIGHT_DOWN = 'lightDown'
LIGHT_UP = 'lightUp'
LIGHT_GRID = 'lightGrid'
LIGHT_TRELLIS = 'lightTrellis'
GRAY125 = 'gray125'
GRAY0625 = 'gray0625'
class unifyxl.BorderStyle(*values)[source]

Line style of a Side; None means no line.

THIN = 'thin'
MEDIUM = 'medium'
DASHED = 'dashed'
DOTTED = 'dotted'
THICK = 'thick'
DOUBLE = 'double'
HAIR = 'hair'
MEDIUM_DASHED = 'mediumDashed'
DASH_DOT = 'dashDot'
MEDIUM_DASH_DOT = 'mediumDashDot'
DASH_DOT_DOT = 'dashDotDot'
MEDIUM_DASH_DOT_DOT = 'mediumDashDotDot'
SLANT_DASH_DOT = 'slantDashDot'
class unifyxl.HorizontalAlignment(*values)[source]

Horizontal alignment of an Alignment.

GENERAL = 'general'
LEFT = 'left'
CENTER = 'center'
RIGHT = 'right'
FILL = 'fill'
JUSTIFY = 'justify'
CENTER_CONTINUOUS = 'centerContinuous'
DISTRIBUTED = 'distributed'
class unifyxl.VerticalAlignment(*values)[source]

Vertical alignment of an Alignment.

TOP = 'top'
CENTER = 'center'
BOTTOM = 'bottom'
JUSTIFY = 'justify'
DISTRIBUTED = 'distributed'
class unifyxl.UnderlineStyle(*values)[source]

Underline of a Font; None means no underline.

SINGLE = 'single'
DOUBLE = 'double'
SINGLE_ACCOUNTING = 'singleAccounting'
DOUBLE_ACCOUNTING = 'doubleAccounting'
class unifyxl.VertAlign(*values)[source]

Superscript or subscript of a Font; None means normal text.

SUPERSCRIPT = 'superscript'
SUBSCRIPT = 'subscript'

Colors

class unifyxl.Color(rgb, theme=None, tint=0.0)[source]

An immutable RGB color with an optional theme reference and tint.

rgb holds the resolved visible color. Direct construction normalizes the RGB input but does not resolve theme or apply tint; use theme_color() or unifyxl.Workbook.theme_color() for resolution. Equality compares rgb, theme, and tint. A Color is never equal to a string; compare color.rgb to test visible colors.

Use dataclasses.replace(color, **changes) to create a modified copy. Changing theme metadata this way does not recalculate rgb. An xlsx file can preserve the theme reference; xls stores only the RGB palette result.

rgb

Required visible color, normalized to uppercase "RRGGBB". Construction also accepts "#RRGGBB", eight-digit ARGB with optional # (alpha is discarded), or a three-integer RGB tuple with components in 0..255. No default.

Type:

str

theme

Theme slot in 0..11, in THEME_COLOR_NAMES order. Defaults to None for plain RGB. Booleans are rejected.

Type:

int | None

tint

Theme tint in -1.0..1.0, defaulting to 0.0. Nonzero tint requires a theme; booleans are rejected.

Type:

float

Raises:
  • ValueError – The RGB notation, theme index, or tint is invalid, or a nonzero tint is given without a theme.

  • TypeError – The RGB input is neither a string nor a tuple.

classmethod theme_color(index, tint=0.0, theme_colors=('FFFFFF', '000000', 'EEECE1', '1F497D', '4F81BD', 'C0504D', '9BBB59', '8064A2', '4BACC6', 'F79646', '0000FF', '800080'))[source]

Resolve a theme slot and tint into a color with theme metadata.

Parameters:
  • index (int) – 0-based theme slot in THEME_COLOR_NAMES order, normally 0..11. Must also exist in theme_colors; booleans are rejected.

  • tint (float) – Number in -1.0..1.0; negative darkens and positive lightens. Defaults to 0.0. Booleans are rejected.

  • theme_colors (tuple[str, ...] | list[str]) – RGB strings indexed by theme slot. Defaults to the 12 Office 2007-2010 colors in DEFAULT_THEME_COLORS.

Returns:

A Color containing the resolved RGB, slot index, and tint.

Raises:
  • ValueError – The index, tint, or selected RGB value is invalid.

  • TypeError – The selected RGB input has an unsupported type.

Return type:

Color

property is_theme: bool

Read-only flag indicating whether a theme slot is present.

Type:

bool

without_theme()[source]

Remove theme metadata while keeping the resolved visible color.

Returns:

A plain RGB Color with zero tint, or this instance if already plain.

Return type:

Color

class unifyxl.ThemeColor(*values)[source]

Theme color slots, for Workbook.theme_color() and Color.theme.

The values are the theme indexes that cell colors use in xlsx (<color theme="4"/>), which follow THEME_COLOR_NAMES. Note that this order puts the light color first (LIGHT1 = 0, DARK1 = 1), while the theme XML itself lists dk1 before lt1.

LIGHT1 = 0

Light 1 (lt1), usually the background (white).

DARK1 = 1

Dark 1 (dk1), usually the text (black).

LIGHT2 = 2

Light 2 (lt2).

DARK2 = 3

Dark 2 (dk2).

ACCENT1 = 4

Accent 1 (accent1).

ACCENT2 = 5

Accent 2 (accent2).

ACCENT3 = 6

Accent 3 (accent3).

ACCENT4 = 7

Accent 4 (accent4).

ACCENT5 = 8

Accent 5 (accent5).

ACCENT6 = 9

Accent 6 (accent6).

Hyperlink (hlink).

Followed hyperlink (folHlink).

unifyxl.ColorLike

Represent a union type

E.g. for int | str

unifyxl.THEME_COLOR_NAMES = ('lt1', 'dk1', 'lt2', 'dk2', 'accent1', 'accent2', 'accent3', 'accent4', 'accent5', 'accent6', 'hlink', 'folHlink')

Built-in immutable sequence.

If no argument is given, the constructor returns an empty tuple. If iterable is specified the tuple is initialized from iterable’s items.

If the argument is a tuple, the return value is the same object.

unifyxl.normalize_color(value)[source]

Normalize a color input while preserving existing color metadata.

Parameters:

value (Color | str | tuple[int, int, int] | None) – A Color, None, a six-digit RGB or eight-digit ARGB hex string (optionally prefixed by #), or a three-integer RGB tuple with components in 0..255. Alpha is discarded from ARGB input.

Returns:

The input unchanged for Color and None; otherwise a Color with uppercase RGB. None represents the automatic application color.

Raises:
  • ValueError – A string or tuple is not valid RGB or ARGB input.

  • TypeError – The input has an unsupported type.

Return type:

Color | None

Example

Normalize a hex string or RGB tuple:

normalize_color("#ff0000").rgb  # "FF0000"
normalize_color((0, 128, 255)).rgb  # "0080FF"

Shapes

Shapes of xlsx files are available from Worksheet.shapes.

class unifyxl.Shape(drawing, anchor, el, parent=None)[source]

A handle to a shape, picture, chart, connector or group on a sheet.

Assigning to a property changes the shape in the workbook; it is written by the next save. Assigning to a removed shape raises ValueError. Obtain handles from Worksheet.shapes, or from shapes of a group. Handles compare equal when they refer to the same object. Lengths are in points (1/72 inch).

Properties that an object does not have are empty: a chart has no text, and a picture reports no fill unless one is set behind it.

property worksheet: XlsxWorksheet

Sheet the shape is on; read-only.

Type:

Worksheet

property parent: Shape | None

Group containing the shape; read-only.

Type:

Shape | None

property element: Element

The shape’s XML; read-only.

Gives access to properties this class does not model.

Type:

xml.etree.ElementTree.Element

property kind: ShapeKind

What the handle stands for; read-only.

Type:

ShapeKind

property id: int | None

Identifier within the drawing; read-only.

Type:

int | None

property name: str

Name shown in Excel’s selection pane.

Type:

str

property description: str

Alternative text. Assign "" to remove it.

Type:

str

property hidden: bool

Whether the shape itself is hidden.

Type:

bool

property shapes: tuple[Shape, ...]

Members of a group, back to front; read-only.

Empty for anything but a group.

Type:

tuple[Shape, …]

property geometry: str | None

DrawingML preset name such as "rect"; read-only.

None for a custom outline or an object without one.

Type:

str | None

property rotation: float

Clockwise rotation in degrees.

Charts and other graphic frames cannot be rotated (ValueError). A shape turned on its side near the top or left edge of the sheet is moved so that it stays on the sheet.

Type:

float

property flip_horizontal: bool

Whether the shape is mirrored left to right.

Type:

bool

property flip_vertical: bool

Whether the shape is mirrored top to bottom.

Type:

bool

property anchor: TwoCellAnchor | OneCellAnchor | AbsoluteAnchor

How the shape is attached to the sheet.

Members of a group report the anchor of the outermost group, and cannot be assigned one. A range such as "B2:D5" or a CellRange may also be assigned.

Type:

ShapeAnchor

property bounds: ShapeBounds

Rectangle before rotation, on the sheet; read-only.

For a member of a group, the rectangle is centered where the member is drawn, with scaling, mirroring and rotation of the groups applied to its center; the size is the one before any rotation.

This is the rectangle stored in the file, which Excel updates when it saves. If none is stored, and for charts, it is worked out from anchor, where column widths are approximate because they depend on the default font.

Type:

ShapeBounds

property fill: ShapeFill

Background, including one set by the shape’s style.

A solid fill has a color. Gradient, picture and pattern fills only report their kind, and cannot be assigned. The fill of a group only shows in members that take their fill from the group.

Type:

ShapeFill

property line: ShapeLine

Outline, or the stroke of a connector.

Assigning keeps settings this class does not model, such as arrow heads.

Type:

ShapeLine

property text: str

The shape’s text; paragraphs are separated by "\n".

Assigning keeps the formatting of the first run and paragraph, and removes text_link. Only shapes and text boxes have text.

Type:

str

property paragraphs: tuple[TextParagraph, ...]

The text with its formatting.

Assigning replaces the formatting of all runs and paragraphs, and removes text_link.

Type:

tuple[TextParagraph, …]

Formula of the cell the text comes from; read-only.

Type:

str | None

class unifyxl.TwoCellAnchor(start, end, placement=Placement.MOVE_AND_SIZE)[source]

A position given by its top-left and bottom-right points.

start

Top-left point.

Type:

AnchorPoint

end

Bottom-right point.

Type:

AnchorPoint

placement

Whether the shape moves and resizes with cells.

Type:

Placement

class unifyxl.OneCellAnchor(start, width, height)[source]

A position given by its top-left point and a fixed size.

start

Top-left point.

Type:

AnchorPoint

width

Width in points.

Type:

float

height

Height in points.

Type:

float

class unifyxl.AbsoluteAnchor(left, top, width, height)[source]

A position on the sheet, independent of cells.

left

Distance from the sheet’s left edge, in points.

Type:

float

top

Distance from the sheet’s top edge, in points.

Type:

float

width

Width in points.

Type:

float

height

Height in points.

Type:

float

class unifyxl.AnchorPoint(row, column, row_offset=0.0, column_offset=0.0)[source]

A point inside a cell.

row

1-based row.

Type:

int

column

1-based column.

Type:

int

row_offset

Distance below the cell’s top edge, in points.

Type:

float

column_offset

Distance right of the cell’s left edge, in points.

Type:

float

unifyxl.ShapeAnchor

Represent a union type

E.g. for int | str

class unifyxl.ShapeBounds(left, top, width, height)[source]

A rectangle on the sheet, in points from its top-left corner.

left

Left edge.

Type:

float

top

Top edge.

Type:

float

width

Width.

Type:

float

height

Height.

Type:

float

class unifyxl.ShapeFill(kind=FillKind.NONE, color=None, transparency=0.0)[source]

How an area or a line is painted.

kind

Kind of fill.

Type:

FillKind

color

Color of a solid fill; None for other kinds, or if the color cannot be resolved.

Type:

Color | None

transparency

0.0 (opaque) to 1.0, for solid fills.

Type:

float

classmethod solid(color, transparency=0.0)[source]

Make a solid fill.

Parameters:
Returns:

The fill.

Return type:

ShapeFill

classmethod none()[source]

Make a fill that paints nothing.

Returns:

The fill.

Return type:

ShapeFill

class unifyxl.ShapeLine(fill=<factory>, width=0.75, dash=LineDash.SOLID)[source]

The outline of a shape, or the stroke of a connector.

fill

Paint of the line; FillKind.NONE for no line.

Type:

ShapeFill

width

Width in points.

Type:

float

dash

Dash style; None for a custom pattern.

Type:

LineDash | None

class unifyxl.TextParagraph(runs=(), alignment=None)[source]

One paragraph of a shape’s text.

runs

Runs, in order.

Type:

tuple[TextRun, …]

alignment

Alignment; None if inherited.

Type:

TextAlignment | None

property text: str

The text of all runs; read-only.

Type:

str

class unifyxl.TextRun(text, font_name=None, size=None, bold=None, italic=None, underline=None, color=None)[source]

Text with uniform formatting; None means inherited or default.

text

Text. A line break within a paragraph is "\n".

Type:

str

font_name

Latin font name.

Type:

str | None

size

Font size in points.

Type:

float | None

bold

Bold.

Type:

bool | None

italic

Italic.

Type:

bool | None

underline

Whether any underline is applied.

Type:

bool | None

color

Text color.

Type:

Color | None

class unifyxl.ShapeKind(*values)[source]

Kind of object a unifyxl.Shape stands for.

SHAPE = 'shape'
TEXT_BOX = 'textBox'
CONNECTOR = 'connector'
GROUP = 'group'
PICTURE = 'picture'
CHART = 'chart'
OTHER = 'other'
class unifyxl.FillKind(*values)[source]

Kind of a ShapeFill.

NONE = 'none'
SOLID = 'solid'
GRADIENT = 'gradient'
PICTURE = 'picture'
PATTERN = 'pattern'
class unifyxl.LineDash(*values)[source]

Dash style of a ShapeLine (DrawingML preset names).

SOLID = 'solid'
DOT = 'dot'
DASH = 'dash'
LONG_DASH = 'lgDash'
DASH_DOT = 'dashDot'
LONG_DASH_DOT = 'lgDashDot'
LONG_DASH_DOT_DOT = 'lgDashDotDot'
SYSTEM_DASH = 'sysDash'
SYSTEM_DOT = 'sysDot'
SYSTEM_DASH_DOT = 'sysDashDot'
SYSTEM_DASH_DOT_DOT = 'sysDashDotDot'
class unifyxl.Placement(*values)[source]

How a shape follows the cells under it.

MOVE_AND_SIZE = 'twoCell'
MOVE = 'oneCell'
FREE = 'absolute'
class unifyxl.TextAlignment(*values)[source]

Horizontal alignment of a TextParagraph.

LEFT = 'l'
CENTER = 'ctr'
RIGHT = 'r'
JUSTIFY = 'just'
JUSTIFY_LOW = 'justLow'
DISTRIBUTED = 'dist'
THAI_DISTRIBUTED = 'thaiDist'

Ranges and coordinates

class unifyxl.CellRange(min_row, min_col, max_row, max_col)[source]

An immutable, inclusive rectangle of cells using 1-based indexes.

All four fields are required. Use dataclasses.replace(range_, **changes) to create a modified copy; the new bounds are validated. Instances support ordering by their fields and membership tests with A1 references or (row, column) tuples.

min_row

First row, in 1..MAX_ROW; no default.

Type:

int

min_col

First column, in 1..MAX_COLUMN; no default.

Type:

int

max_row

Last row, in min_row..MAX_ROW; no default.

Type:

int

max_col

Last column, in min_col..MAX_COLUMN; no default.

Type:

int

Raises:

ValueError – A bound is outside the xlsx limits, or the minimum exceeds the maximum on either axis. Boolean bounds are not accepted.

classmethod parse(ref)[source]

Parse a single cell or inclusive range, normalizing endpoint order.

Parameters:

ref (str | CellRange) – A reference such as "B2" or "C3:A1", or a CellRange. Cell coordinates follow parse_coordinate().

Returns:

A range with sorted bounds. An existing CellRange is returned unchanged; a single cell becomes a one-cell range.

Raises:

ValueError – The reference syntax or a coordinate is invalid.

Return type:

CellRange

property coord: str

Read-only A1 range reference, including both endpoints.

A one-cell range is written as, for example, "B2:B2".

Type:

str

property start: tuple[int, int]

Read-only top-left (row, column) indexes.

Type:

tuple[int, int]

property size: tuple[int, int]

Read-only size as (rows, columns).

Type:

tuple[int, int]

intersects(other)[source]

Test whether two ranges share at least one cell.

Parameters:

other (CellRange) – The range to compare with this range.

Returns:

Whether the rectangles overlap, including their boundary cells.

Return type:

bool

cells()[source]

Iterate over every coordinate in row-major order.

Yields:

A (row, column) tuple of 1-based indexes for each included cell.

Return type:

Iterator[tuple[int, int]]

unifyxl.column_letter(index)[source]

Convert a positive, 1-based column index to uppercase letters.

Unlike column_index, this helper accepts indexes beyond the xlsx limit.

Parameters:

index (int) – Positive integer column index; booleans are not accepted.

Returns:

Excel column letters, such as "A" for 1 or "AB" for 28.

Raises:

ValueError – index is not a positive integer.

Return type:

str

unifyxl.column_index(col)[source]

Convert column letters or an index to a 1-based column index.

Parameters:

col (str | int) – Case-insensitive ASCII column letters from A through XFD, or an integer from 1 through MAX_COLUMN. Booleans are not accepted.

Returns:

The validated integer column index.

Raises:

ValueError – The column notation is invalid or outside the xlsx limits.

Return type:

int

unifyxl.coordinate(row, col)[source]

Build an A1 reference from 1-based row and column indexes.

Parameters:
  • row (int) – Integer row index from 1 through MAX_ROW.

  • col (int) – Positive integer column index. There is no upper column bound in this helper. Booleans are not accepted for either index.

Returns:

An uppercase reference without dollar signs, such as "B3".

Raises:

ValueError – The row is invalid or the column is not a positive integer.

Return type:

str

unifyxl.parse_coordinate(coord)[source]

Parse an A1 reference into 1-based row and column indexes.

Parameters:

coord (str) – A single cell reference, such as "B3" or "$b$3". Surrounding whitespace is ignored; sheet names are not accepted.

Returns:

A (row, column) tuple, such as (3, 2) for "B3".

Raises:

ValueError – The reference is invalid or outside the xlsx sheet limits.

Return type:

tuple[int, int]

Exceptions

exception unifyxl.UnifyXLError[source]

Bases: Exception

Base exception for errors defined by unifyxl.

Catch this class to handle MergedCellError, FormatLimitError, UnsupportedFeatureError, and UnsupportedFormatError together. Ordinary validation and backend errors are not wrapped in this class.

exception unifyxl.MergedCellError[source]

Bases: UnifyXLError

A value was assigned to a non-anchor cell of a merged range.

Only the top-left cell may hold a value. Assigning None to any other cell of the range raises this error too; use unmerge_cells before writing separate values.

exception unifyxl.FormatLimitError[source]

Bases: UnifyXLError, ValueError

Data exceeds a supported Excel format limit.

Both formats reject assigned strings longer than 32,767 characters. Xls also rejects writes beyond 65,536 rows or 256 columns, and saving more than 4,000 distinct output cell formats. The style count is evaluated after palette mapping and other xls output normalization. Xls palette overflow uses nearest-color approximation with a warning rather than this error.

This exception also inherits from ValueError.

exception unifyxl.UnsupportedFormatError[source]

Bases: UnifyXLError, ValueError

The input signature is neither an xlsx ZIP nor an xls OLE2 container.

Raised during format detection, regardless of the filename extension. A recognized signature does not guarantee a valid workbook; parsing failures are reported by the underlying backend. This exception also inherits from ValueError.

exception unifyxl.UnsupportedFeatureError[source]

Bases: UnifyXLError, NotImplementedError

The workbook’s format does not support the requested feature.

Raised by Worksheet.shapes of xls workbooks, whose drawings cannot be read. This exception also inherits from NotImplementedError.

exception unifyxl.ShapeLossWarning[source]

Bases: UserWarning

Shapes of the workbook are missing from the file or workbook written.

Turn it into an error with warnings.simplefilter("error", unifyxl.ShapeLossWarning) to stop before anything is written.

Format-specific classes

load_workbook() and new_workbook() return one of these. They implement Workbook and Worksheet; the xlsx classes also give access to the wrapped openpyxl objects.

class unifyxl._xlsx.XlsxWorkbook(owb, path=None)[source]

A workbook backed by openpyxl, including xlsm files with VBA.

Use unifyxl.new_workbook() or unifyxl.load_workbook() for normal construction. Untouched features survive a load/save round trip to the extent supported by openpyxl. Conversion uses only the shared model. The common cell API uses 1-based coordinates; sheet positions are 0-based.

Parameters:
  • owb (openpyxl.Workbook) – Existing openpyxl workbook to wrap; it is retained, not copied.

  • path (str | None) – Original source path, or None for a workbook without a path. Defaults to None; saving does not update it.

format

The backend identifier "xlsx", also for xlsm input.

Type:

str

path

Original source path, if provided.

Type:

str | None

property openpyxl_workbook: Workbook

Wrapped workbook; read-only property.

The property cannot be reassigned, but the returned workbook is mutable. Direct changes affect the same workbook used by unifyxl and expose openpyxl features outside the common API, bypassing unifyxl validation.

Type:

openpyxl.Workbook

property worksheets: list[Worksheet]

Read-only property returning worksheets in tab order.

The list is a snapshot. Use create_sheet and remove_sheet to change the workbook’s sheets.

Type:

list[Worksheet]

class unifyxl._xlsx.XlsxWorksheet(workbook, ows)[source]

A 1-based worksheet wrapper backed by an openpyxl worksheet.

Use the inherited Worksheet API for shared operations, or openpyxl_worksheet for features outside the common model. Changing one style part preserves unrelated openpyxl formatting. Cell handles use xlsx bounds of 1,048,576 rows and 16,384 columns.

Parameters:
  • workbook (XlsxWorkbook) – Owning XlsxWorkbook.

  • ows – Existing openpyxl worksheet to wrap; it is retained, not copied.

property openpyxl_worksheet

Wrapped worksheet; read-only.

The property cannot be reassigned, but the returned object is mutable. Direct changes affect the same worksheet used by unifyxl and provide access to features outside the common API, bypassing unifyxl validation.

Type:

openpyxl.worksheet.worksheet.Worksheet

property shapes: tuple[Shape, ...]

Shapes on the sheet, back to front (xlsx only).

Includes text boxes, connectors, groups, pictures and charts. Members of a group are available from the group’s own shapes. Pictures and charts added through openpyxl appear after saving and loading.

Raises:

UnsupportedFeatureError – The workbook is an xls workbook.

Type:

tuple[Shape, …]

add_shape(anchor, geometry='rect', *, text='', fill=None, line=None, name=None)[source]

Add a shape in front of the others (xlsx only).

Parameters:
  • anchor (TwoCellAnchor | OneCellAnchor | AbsoluteAnchor | CellRange | str) – Position: a range such as "B2:D5", or a TwoCellAnchor, OneCellAnchor or AbsoluteAnchor.

  • geometry (str) – DrawingML preset name, such as "rect", "roundRect", "ellipse" or "rightArrow".

  • text (str) – Text; "\n" separates paragraphs.

  • fill (ShapeFill | None) – Background. Defaults to the theme’s style in accent color 1.

  • line (ShapeLine | None) – Outline. Defaults to the theme’s style in accent color 1.

  • name (str | None) – Name; generated if None.

Returns:

A handle to the new shape.

Raises:
Return type:

Shape

add_text_box(anchor, text='', *, fill=None, line=None, name=None)[source]

Add a text box in front of the other shapes (xlsx only).

Parameters:
Returns:

A handle to the new text box.

Raises:
Return type:

Shape

add_connector(anchor, geometry='line', *, flip_horizontal=False, flip_vertical=False, line=None, name=None)[source]

Add a line or connector in front of the other shapes (xlsx only).

It runs from the top left to the bottom right of the anchor unless it is flipped, and is not attached to other shapes.

Parameters:
  • anchor (TwoCellAnchor | OneCellAnchor | AbsoluteAnchor | CellRange | str) – Position, as for add_shape().

  • geometry (str) – DrawingML preset name, such as "line" or "bentConnector3".

  • flip_horizontal (bool) – Mirror left to right.

  • flip_vertical (bool) – Mirror top to bottom.

  • line (ShapeLine | None) – Stroke. Defaults to the theme’s style in accent color 1.

  • name (str | None) – Name; generated if None.

Returns:

A handle to the new connector.

Raises:
Return type:

Shape

remove_shape(shape)[source]

Remove a shape, picture, chart, connector or group (xlsx only).

Parameters:

shape (Shape) – A handle obtained from this sheet, or from one of its groups.

Raises:
class unifyxl._xls.XlsWorkbook(default_style=None)[source]

An xls workbook read by xlrd and written from memory by xlwt.

Loading retains cached formula results, not formula expressions. Saving rebuilds the file from the common model, losing unsupported features such as charts, images, comments, and data validation. Newly assigned formulas are parsed by xlwt when saved; their results are not calculated.

Xls supports 65,536 rows, 256 columns, 4,000 distinct output cell formats, and 56 palette colors. Palette overflow warns and uses nearest colors. Themes can be retained in memory for conversion, but xls stores only RGB palette values. Sheet positions are 0-based and cell coordinates 1-based.

Parameters:

default_style (CellStyle | None) – Style used for cells without explicit formatting. None defaults to an otherwise unformatted style with Arial 10-point text.

format

The backend identifier "xls".

Type:

str

path

Source path when loaded from a path, otherwise None. Saving does not update it.

Type:

str | None

property worksheets: list[Worksheet]

Read-only property returning worksheets in tab order.

The list is a snapshot. Use create_sheet and remove_sheet to change the workbook’s sheets.

Type:

list[Worksheet]

class unifyxl._xls.XlsWorksheet(workbook, title)[source]

An in-memory xls worksheet with 1-based cell coordinates.

Writes, merges, dimensions, and freeze panes enforce xls bounds of 65,536 rows and 256 columns. Reads within the broader xlsx bounds may return empty values beyond those limits. Formatting uses the shared immutable model.

Parameters:
  • workbook (XlsWorkbook) – Owning XlsWorkbook.

  • title (str) – Worksheet name. Normal public creation through Workbook.create_sheet validates the title before construction.

Constants

unifyxl.styles.DEFAULT_THEME_COLORS: tuple[str, ...] = ('FFFFFF', '000000', 'EEECE1', '1F497D', '4F81BD', 'C0504D', '9BBB59', '8064A2', '4BACC6', 'F79646', '0000FF', '800080')

Office 2007-2010 RGB defaults, in THEME_COLOR_NAMES order. New workbooks use these colors; xls files have no native theme.

unifyxl.utils.MAX_ROW = 1048576

Maximum 1-based row index in an xlsx worksheet (1,048,576).

unifyxl.utils.MAX_COLUMN = 16384

Maximum 1-based column index in an xlsx worksheet (16,384, or XFD).

unifyxl.styles.apply_tint(rgb, tint)[source]

Lighten or darken RGB using Excel-style HLS luminance adjustment.

Parameters:
  • rgb (str) – A six-digit "RRGGBB" hexadecimal string.

  • tint (float) – Amount in -1.0..1.0. Negative values darken toward black; positive values lighten toward white. Zero returns rgb unchanged. The range is not validated by this helper.

Returns:

The tinted RGB string, in uppercase when a nonzero tint is applied.

Raises:

ValueError – A component cannot be parsed as hexadecimal for nonzero tint.

Return type:

str