Source code for unifyxl

"""Read, write, and convert Excel workbooks through one API.

The xlsx backend wraps openpyxl and also accepts xlsm files. The xls backend
uses xlrd for reading and xlwt for writing. Both expose cell values, immutable
styles, merged ranges, dimensions, and freeze panes through the same interface.
Rows and columns use 1-based indexes; worksheet positions use 0-based indexes.

Example:
    Create a workbook, format a cell, and save it in either format::

        import unifyxl

        wb = unifyxl.new_workbook()
        ws = wb.active
        ws["A1"] = "Report"
        ws["A1"].font = ws["A1"].font.replace(bold=True)
        ws["A1"].bg_color = "FFFF00"
        ws.merge_cells("A1:C1")
        wb.save("report.xlsx")
        wb.save("report.xls")
"""

from __future__ import annotations

import os
from typing import IO

from ._base import Cell, Workbook, Worksheet
from ._drawing import Shape
from .exceptions import (
    FormatLimitError,
    MergedCellError,
    ShapeLossWarning,
    UnifyXLError,
    UnsupportedFeatureError,
    UnsupportedFormatError,
)
from .shapes import (
    AbsoluteAnchor,
    AnchorPoint,
    FillKind,
    LineDash,
    OneCellAnchor,
    Placement,
    ShapeAnchor,
    ShapeBounds,
    ShapeFill,
    ShapeKind,
    ShapeLine,
    TextAlignment,
    TextParagraph,
    TextRun,
    TwoCellAnchor,
)
from .styles import (
    THEME_COLOR_NAMES,
    Alignment,
    Border,
    BorderStyle,
    CellStyle,
    Color,
    ColorLike,
    Fill,
    FillPattern,
    Font,
    HorizontalAlignment,
    Side,
    ThemeColor,
    UnderlineStyle,
    VertAlign,
    VerticalAlignment,
    normalize_color,
)
from .utils import CellRange, column_index, column_letter, coordinate, parse_coordinate

__all__ = [
    "THEME_COLOR_NAMES",
    "AbsoluteAnchor",
    "Alignment",
    "AnchorPoint",
    "Border",
    "BorderStyle",
    "Cell",
    "CellRange",
    "CellStyle",
    "Color",
    "ColorLike",
    "Fill",
    "FillKind",
    "FillPattern",
    "Font",
    "FormatLimitError",
    "HorizontalAlignment",
    "LineDash",
    "MergedCellError",
    "OneCellAnchor",
    "Placement",
    "Shape",
    "ShapeAnchor",
    "ShapeBounds",
    "ShapeFill",
    "ShapeKind",
    "ShapeLine",
    "ShapeLossWarning",
    "Side",
    "TextAlignment",
    "TextParagraph",
    "TextRun",
    "ThemeColor",
    "TwoCellAnchor",
    "UnderlineStyle",
    "UnifyXLError",
    "UnsupportedFeatureError",
    "UnsupportedFormatError",
    "VertAlign",
    "VerticalAlignment",
    "Workbook",
    "Worksheet",
    "column_index",
    "column_letter",
    "coordinate",
    "detect_format",
    "load_workbook",
    "new_workbook",
    "normalize_color",
    "parse_coordinate",
]

_OLE2_MAGIC = b"\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1"
_ZIP_MAGIC = b"PK\x03\x04"


[docs] def detect_format(source: str | os.PathLike | IO[bytes]) -> str: """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. Args: source: 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. """ if isinstance(source, (str, os.PathLike)): with open(source, "rb") as f: head = f.read(8) else: pos = source.tell() head = source.read(8) source.seek(pos) if head.startswith(_ZIP_MAGIC): return "xlsx" if head == _OLE2_MAGIC: return "xls" raise UnsupportedFormatError("not an xlsx or xls file")
[docs] def load_workbook( source: str | os.PathLike | IO[bytes], *, data_only: bool = False, ) -> Workbook: """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. Args: source: 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: 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 :class:`Workbook`. Raises: UnsupportedFormatError: The source has neither a ZIP nor OLE2 signature. OSError: The source cannot be opened or read. Example: Read the active sheet's values:: wb = load_workbook("report.xlsx", data_only=True) rows = wb.active.values() """ fmt = detect_format(source) if fmt == "xlsx": from ._xlsx import XlsxWorkbook return XlsxWorkbook.load(source, data_only=data_only) from ._xls import XlsWorkbook return XlsWorkbook.load(source)
[docs] def new_workbook(format: str = "xlsx", *, _empty: bool = False) -> Workbook: """Create a workbook with one worksheet named ``"Sheet"`` by default. Args: format: Output model, either ``"xlsx"`` (the default) or ``"xls"``. _empty: 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 :class:`Workbook` with no associated source path. Raises: ValueError: ``format`` is neither ``"xlsx"`` nor ``"xls"``. """ if format == "xlsx": from ._xlsx import XlsxWorkbook return XlsxWorkbook.new(with_sheet=not _empty) if format == "xls": from ._xls import XlsWorkbook return XlsWorkbook.new(with_sheet=not _empty) raise ValueError(f"unknown format: {format!r} (expected 'xlsx' or 'xls')")