Metadata-Version: 2.4
Name: unifyxl
Version: 0.5.0
Summary: Read and write xlsx and xls without losing merged-cell formatting: one API over openpyxl and xlrd + xlwt
Keywords: excel,xlsx,xls,openpyxl,xlrd,xlwt,spreadsheet
Author: skrtk98
License-Expression: MIT
License-File: LICENSE
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Office/Business :: Financial :: Spreadsheet
Classifier: Typing :: Typed
Requires-Dist: openpyxl>=3.1.5
Requires-Dist: xlrd>=2.0.2
Requires-Dist: xlwt>=1.3.0
Requires-Python: >=3.11
Project-URL: Homepage, https://github.com/skrtk98/unifyxl
Project-URL: Documentation, https://skrtk98.github.io/unifyxl/
Project-URL: Repository, https://github.com/skrtk98/unifyxl
Project-URL: Issues, https://github.com/skrtk98/unifyxl/issues
Project-URL: Wiki, https://github.com/skrtk98/unifyxl/wiki
Description-Content-Type: text/markdown

# unifyxl

English | [日本語](https://github.com/skrtk98/unifyxl/blob/main/README.ja.md)

Read and write Excel files without losing the formatting of merged cells, in both xlsx and xls.

When openpyxl loads an xlsx file, every cell of a merged range except the top-left one loses its
background color, and only the outer edge of its borders survives. Save the workbook again and that
formatting is gone from the file. unifyxl re-reads each merged cell's style from the sheet XML and
restores it:

```text
Merged range B2:D3, every cell yellow with thin borders on all sides (as saved by Excel)

            openpyxl                         unifyxl
B2 (anchor) yellow, borders L/R/T/B          yellow, borders L/R/T/B
C2          no fill, border T only           yellow, borders L/R/T/B
C3          no fill, border B only           yellow, borders L/R/T/B
```

The same API also handles legacy xls (via xlrd + xlwt), and converts between the two formats with
formatting intact. Unlike pandas, it reads and writes more than values:

- Formatting: fonts, background colors (fills), borders, alignment, number formats
- Merged cells, including the formatting of every cell in the range
- Column widths, row heights, freeze panes
- Theme colors (kept as theme references in xlsx)
- Shapes (xlsx): read, edit, add and remove them, including position, fill, outline and text

## Installation

```sh
uv add unifyxl        # or: pip install unifyxl
```

Requires Python 3.11 or later. Dependencies: openpyxl, xlrd, xlwt. To install the latest development version, use `uv add git+https://github.com/skrtk98/unifyxl`.

## Usage

```python
import unifyxl
from unifyxl import (
    Alignment, Border, BorderStyle, Fill, Font, HorizontalAlignment, Side,
    ThemeColor, VerticalAlignment,
)

# Load (the format is detected from the content, not the extension)
wb = unifyxl.load_workbook("input.xls")      # same for .xlsx / .xlsm
ws = wb.active                                # or wb["Sheet1"], wb[0]

cell = ws["B2"]                               # or ws.cell(2, 2), ws[2, 2]
cell.value                                    # value
cell.bg_color                                 # background Color (solid fills only; None otherwise)
cell.bg_color.rgb                             # "RRGGBB"
cell.font.bold, cell.font.color               # font
cell.border.bottom.style                      # BorderStyle.THIN, etc. (equals "thin")
cell.alignment.horizontal                     # HorizontalAlignment.CENTER, etc.
cell.number_format                            # "#,##0", etc.
cell.merged_range                             # merged range as CellRange, or None
ws.merged_ranges                              # all merged ranges in the sheet

# Write
ws["A1"] = "Header"
ws["A1"].font = Font(bold=True, size=14, color="FFFFFF")
ws["A1"].bg_color = "4472C4"
ws["A2"].bg_color = wb.theme_color(ThemeColor.ACCENT1, tint=0.4)   # theme color (kept as a theme reference in xlsx)
ws["A1"].border = Border.all(BorderStyle.THIN, "000000")
ws["A1"].alignment = Alignment(HorizontalAlignment.CENTER, VerticalAlignment.CENTER)
ws.merge_cells("A1:D1")
ws.set_column_width("A", 20)
ws.set_row_height(1, 30)
ws.freeze_panes = "A2"

# Change only part of a style (style objects are immutable; replace() makes a new one)
ws["B2"].font = ws["B2"].font.replace(italic=True)

# Copy another cell's whole style (works across formats too)
ws["C3"].style = ws["A1"].style

wb.save("output.xls")
wb.save("output.xlsx")                        # a different extension converts on save
```

Shapes in an xlsx sheet:

```python
for shape in ws.shapes:                       # text boxes, connectors, groups, pictures, charts too
    shape.kind, shape.name, shape.text        # ShapeKind.SHAPE, "Rectangle 1", "Hello"
    shape.anchor                              # cells (1-based) or sheet position it is attached to
    shape.bounds                              # left, top, width, height in points
    shape.fill.kind, shape.fill.color         # FillKind.SOLID, Color (theme styles are resolved)
    shape.line.width, shape.line.fill.color   # outline
    shape.shapes                              # members of a group

# Add, edit and remove
from unifyxl import LineDash, ShapeFill, ShapeLine

box = ws.add_shape("B2:D5", "roundRect", text="Hello")   # also add_text_box(), add_connector()
box.fill = ShapeFill.solid(wb.theme_color(ThemeColor.ACCENT2, tint=0.4))
box.line = ShapeLine(ShapeFill.solid("FF0000"), width=2, dash=LineDash.DASH)
box.text = "First line\nSecond line"          # keeps the formatting of the first run
box.anchor = "F2:H5"
box.rotation = 15
ws.remove_shape(box)
```

Create a new workbook with `unifyxl.new_workbook("xlsx")` or `unifyxl.new_workbook("xls")`.

## API overview

| Object | Main API |
|---|---|
| Workbook | `sheetnames`, `worksheets`, `active`, `create_sheet()`, `remove_sheet()`, `del wb[name]`, `save()`, `convert()`, `format`, `theme_colors`, `theme_color()` |
| Worksheet | `title`, `cell()`, `ws["A1"]`, `ws["A1:C3"]`, `iter_rows()`, `values()`, `append()`, `max_row`, `max_column`, `merge_cells()`, `unmerge_cells()`, `merged_ranges`, `get/set_column_width()`, `get/set_row_height()`, `freeze_panes` |
| Cell | `value`, `style`, `font`, `fill`, `border`, `alignment`, `number_format`, `bg_color`, `merged_range`, `is_merged`, `is_formula`, `coordinate` |
| Styles | `CellStyle(font, fill, border, alignment, number_format)`, `Font`, `Fill` (`Fill.solid(color)`), `Border` (`Border.all(style, color)`), `Side`, `Alignment`, `Color` (`Color.theme_color(index, tint)`) |

- Row and column numbers are 1-based. Columns can be given as `"A"` or `1`.
- Style names are `StrEnum` members: `BorderStyle`, `FillPattern`, `HorizontalAlignment`, `VerticalAlignment`, `UnderlineStyle`, `VertAlign` (e.g. `BorderStyle.THIN`, `HorizontalAlignment.CENTER`). Each member equals its OOXML string (`BorderStyle.THIN == "thin"`), and values read from cells are always members. Constructors also accept the plain strings at runtime (`Border.all("thin")`) and raise `ValueError` for an invalid name, but type checkers such as mypy and Pyright accept only the members, so typos are caught before running.
- Colors are returned as `Color` objects; `color.rgb` is the `"RRGGBB"` value. `None` means "automatic".
- When setting a color, besides `Color` you can pass `"RRGGBB"`, `"#rrggbb"`, `"AARRGGBB"` or `(r, g, b)`; it is converted to a `Color`.
- `==` between two `Color` objects is true only when `rgb`, `theme` and `tint` all match. A `Color` never equals a string (`Color("FF0000") == "FF0000"` is false). To compare the visible color, write `color.rgb == "FF0000"`.
- xlsx indexed colors are returned as RGB `Color`s. If an RGB or indexed color has a tint, it is returned as the RGB with the tint applied (if you change a style containing that color, it is saved as that tinted RGB; the visible color does not change).
- xlsx theme colors are returned as `Color`s with `color.theme` (the theme color index) and `color.tint` (-1.0 to 1.0). `color.rgb` is the RGB with the tint applied. A theme color and an RGB color are not `==` even if they look the same. `color.without_theme()` gives the color without its theme reference, and `style.without_theme()` does the same for a whole style.
- To specify a theme color, use `wb.theme_color(ThemeColor.ACCENT1, tint=0.4)`. `ThemeColor` is an `IntEnum` of the theme indexes cells refer to: `LIGHT1` (0, lt1), `DARK1` (1, dk1), `LIGHT2` (2), `DARK2` (3), `ACCENT1`-`ACCENT6` (4-9), `HYPERLINK` (10) and `FOLLOWED_HYPERLINK` (11), in `THEME_COLOR_NAMES` order. Light comes before dark here, although the theme XML lists dk1 first. A theme color read from a cell has `color.theme` as a `ThemeColor`. The RGB value is resolved from that workbook's theme. `wb.theme_colors` returns the theme's 12 colors as a tuple of `"RRGGBB"` strings. `Color.theme_color()` resolves the RGB with the Office 2007-2010 default theme (the theme openpyxl writes to new workbooks).
- Theme colors are saved to xlsx as theme references, so they follow a theme change in Excel. The reference is also kept when you change part of a style (e.g. `cell.font = cell.font.replace(bold=True)`).
- Rows range from 1 to 1048576 and columns from 1 to 16384 (A to XFD). Out-of-range values raise `ValueError`.
- Writing a value to a merged cell other than the top-left one raises `MergedCellError`.
- Merging clears the values and styles of all cells except the top-left one, and the top-left cell's borders are carried over to the cells on the edge of the range. If the top-left cell has no right or bottom border, it takes the bottom-right cell's (both formats follow openpyxl's behavior).
- Units: column width is in Excel character units, row height in points. Row heights must be greater than 0 and at most 409 (0 is not allowed because openpyxl does not save it; hiding rows is not supported yet).
- If you need the underlying objects, use `wb.openpyxl_workbook` and `ws.openpyxl_worksheet` (xlsx only).

## Format differences and limitations

### xlsx (openpyxl)
- Column settings without a width (columns that are only grouped or hidden, etc.) are read by openpyxl as width 13. So even if you clear a width with `set_column_width(col, None)`, such columns read back as 13.
- Because the openpyxl objects are wrapped directly, parts you don't touch (comments, data validation, etc.) are saved as far as openpyxl preserves them.
- Plain openpyxl drops the styles of merged cells other than the top-left one on load (it only moves the bottom-right cell's right and bottom borders to the top-left cell). As a result, borders of the top-right and bottom-left cells, fills, number formats and so on are lost. unifyxl re-reads the sheet XML after loading and restores each merged cell's style from the file.
- When you change part of a style (`cell.font = ...` etc.), only the assigned part (font, fill, border, alignment or number format) is changed and the other parts are kept. For example, `cell.font = ...` keeps fills the unifyxl model cannot express, such as gradient fills. Settings the model cannot express inside the assigned part are lost, though (text direction for `cell.alignment = ...`, diagonal borders for `cell.border = ...`).
- Gradient fills cannot be read (they are returned as no fill).
- The theme itself (its color definitions) is read-only and cannot be changed.
- Theme colors in the `srgbClr`, `sysClr`, `scrgbClr` and `hslClr` notations are read. Colors in other notations such as `prstClr`, and colors with color transform child elements such as `lumMod`, are treated as the default theme color, with a warning.
- If you load and save an xlsx whose theme references images (texture fills, etc.), the images are not saved and only the references remain in the theme XML, because openpyxl writes back only the theme XML it loaded. When converting formats, a theme XML that references other parts (has attributes such as `r:embed`) is not carried over; only its color definitions are.

- Shapes are kept when you save as xlsx, with their z-order and the parts they refer to (pictures, SmartArt data, etc.). Pictures and charts that openpyxl could load are written from openpyxl's objects; a picture keeps its other settings (crop, name, hyperlink, etc.) from the file. Pictures that openpyxl cannot load (e.g. without Pillow) are kept as they are.
- Form controls, OLE objects, slicers and timelines are not kept, because openpyxl drops the data they depend on. Converting to another format, or with `convert()`, drops all shapes. In both cases unifyxl issues a `ShapeLossWarning` before writing.
- Saving through `wb.openpyxl_workbook.save()` bypasses this and drops the shapes. References to sheets inside shapes (such as a linked cell) are not updated when a sheet is renamed. Shapes on chart sheets are not kept, and no warning is issued for them.
- Only solid fills (or none) can be assigned. Assigning `paragraphs` replaces all run formatting, and assigning text removes the link to a cell. Connectors are not attached to other shapes, and pictures and charts are added through openpyxl. Charts allow only their name, alternative text, visibility and position to be changed. If the same part of a picture (such as its fill) is changed both here and through openpyxl since loading or the last save, the change made through openpyxl is saved. If a shape in the file has alternative versions for older applications (`mc:AlternateContent`), only the version that is read is edited.
- `shape.bounds` is the rectangle stored in the file. If there is none, and always for charts, it is computed from the anchor, with approximate column widths. Gradient, picture and pattern fills report only their kind.

### xls (xlrd + xlwt)
- Shapes cannot be read: `ws.shapes` raises `UnsupportedFeatureError`.
- xlrd only reads and xlwt only writes. So xls files are converted into an in-memory model on load and rebuilt with xlwt on save. **Charts, images, comments, data validation, conditional formatting and the like are not saved.**
- xlrd cannot read formulas. When you read an xls file, formula cells contain their last calculated value. Writing a string such as `"=A1*2"` saves it as an xlwt formula (formulas xlwt cannot parse raise `ValueError` on save). xlwt does not write calculated results, so reading the file back with unifyxl gives an empty string.
- Colors are assigned to the palette (56 colors). The palette of a loaded file is kept, as are colors referenced by number formats such as `[Color10]`. If there are not enough free slots, the colors used by the fewest cells are replaced by the nearest color, with a warning.
- The limits are 65536 rows × 256 columns and 4000 distinct cell formats. Exceeding them raises `FormatLimitError`, also when converting from xlsx to xls.
- Indentation is limited to 15 (larger values are clipped to 15).
- Integral numbers are returned as `int` (to match xlsx results).
- xls has no themes, so only the RGB value of a theme color is saved. For a workbook loaded from an xls file, `theme_colors` returns the Office 2007-2010 default theme. The in-memory model keeps theme references, so theme colors set in an xls workbook are written as theme references when it is saved as xlsx.
- Converting formats (`convert()`) also carries over the theme's color definitions. Even if you convert an xlsx with a custom theme to xls and back to xlsx in memory, the colors theme references point to do not change. An xls file cannot store a theme, though, so if you save it as xls and read it back, the theme references are gone and only the RGB values remain.

### Both formats
- Values can be `str`, `int`, `float`, `bool`, `datetime`, `date`, `time`, `timedelta`, `Decimal` (converted to `float`) or `None`. NaN and infinity raise `ValueError`; strings longer than 32767 characters raise `FormatLimitError`.
- Assigning a date or time sets a number format such as `yyyy-mm-dd h:mm:ss` automatically if the current number format is not a date format (same as openpyxl). On load, dates are returned as `datetime`, values below 1 as `time`, and elapsed-time formats such as `[h]:mm:ss` as `timedelta`. Time precision is milliseconds in both formats (like openpyxl, microseconds are rounded to milliseconds when the file is saved and read back).
- Assigning a string starting with `"="` creates a formula, and assigning an error value string such as `"#DIV/0!"` creates an error value (same as openpyxl). A plain string starting with "=" read from a file stays a string when saved or converted.
- Inserting or deleting rows and columns, diagonal borders, cell protection and hyperlinks are not supported.

## License

MIT License. See [LICENSE](https://github.com/skrtk98/unifyxl/blob/main/LICENSE).

## Development

```sh
uv sync
uv run pytest
```
