unifyxl
English | 日本語
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:
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
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
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:
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"or1. - Style names are
StrEnummembers: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 raiseValueErrorfor 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
Colorobjects;color.rgbis the"RRGGBB"value.Nonemeans "automatic". - When setting a color, besides
Coloryou can pass"RRGGBB","#rrggbb","AARRGGBB"or(r, g, b); it is converted to aColor. ==between twoColorobjects is true only whenrgb,themeandtintall match. AColornever equals a string (Color("FF0000") == "FF0000"is false). To compare the visible color, writecolor.rgb == "FF0000".- xlsx indexed colors are returned as RGB
Colors. 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
Colors withcolor.theme(the theme color index) andcolor.tint(-1.0 to 1.0).color.rgbis 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, andstyle.without_theme()does the same for a whole style. - To specify a theme color, use
wb.theme_color(ThemeColor.ACCENT1, tint=0.4).ThemeColoris anIntEnumof the theme indexes cells refer to:LIGHT1(0, lt1),DARK1(1, dk1),LIGHT2(2),DARK2(3),ACCENT1-ACCENT6(4-9),HYPERLINK(10) andFOLLOWED_HYPERLINK(11), inTHEME_COLOR_NAMESorder. Light comes before dark here, although the theme XML lists dk1 first. A theme color read from a cell hascolor.themeas aThemeColor. The RGB value is resolved from that workbook's theme.wb.theme_colorsreturns 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_workbookandws.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 forcell.alignment = ..., diagonal borders forcell.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,scrgbClrandhslClrnotations are read. Colors in other notations such asprstClr, and colors with color transform child elements such aslumMod, 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 aShapeLossWarningbefore 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
paragraphsreplaces 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.boundsis 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.shapesraisesUnsupportedFeatureError. - 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 raiseValueErroron 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_colorsreturns 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 tofloat) orNone. NaN and infinity raiseValueError; strings longer than 32767 characters raiseFormatLimitError. - Assigning a date or time sets a number format such as
yyyy-mm-dd h:mm:ssautomatically if the current number format is not a date format (same as openpyxl). On load, dates are returned asdatetime, values below 1 astime, and elapsed-time formats such as[h]:mm:ssastimedelta. 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.
Development
uv sync
uv run pytest
Metadata
Release files for unifyxl 0.5.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| unifyxl-0.5.0.tar.gz | 79.5 kB | With provenance | Details for unifyxl-0.5.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| unifyxl-0.5.0-py3-none-any.whl | Python 3 | none | any | Details for unifyxl-0.5.0-py3-none-any.whl |
Total release size: 165.9 kB
Release files / unifyxl-0.5.0.tar.gz
| Download URL | unifyxl-0.5.0.tar.gz |
|---|---|
| Size | 79.5 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
f6f2d3b1453897c7cad310d8be3f514c367aa48b90f1416bf3caa7ff9f251b00
|
|
BLAKE2b-256 checksum How to use checksums |
522d819d937baca2fde68bce711466eb59a1fa73acda2ae4b5762bf9e2531e46
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 30, 2026.
Transparency logRelease files / unifyxl-0.5.0-py3-none-any.whl
| Download URL | unifyxl-0.5.0-py3-none-any.whl |
|---|---|
| Size | 86.4 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
32700df0615fbb348199f00f708b06f6c6f2220a48b8e26fbf82ee2c25dfcc53
|
|
BLAKE2b-256 checksum How to use checksums |
46160d37cdfc3330ff58b840dcef2bc2a7c601b5865d2a538b53f9c80e4d8d9c
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 30, 2026.
Transparency logSecurity for unifyxl 0.5.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for unifyxl-0.5.0.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 30, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.