unifyxl 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- unifyxl-0.1.0/LICENSE +21 -0
- unifyxl-0.1.0/PKG-INFO +150 -0
- unifyxl-0.1.0/README.md +124 -0
- unifyxl-0.1.0/pyproject.toml +52 -0
- unifyxl-0.1.0/pyproject.toml.orig +44 -0
- unifyxl-0.1.0/src/unifyxl/__init__.py +160 -0
- unifyxl-0.1.0/src/unifyxl/_base.py +1038 -0
- unifyxl-0.1.0/src/unifyxl/_convert.py +47 -0
- unifyxl-0.1.0/src/unifyxl/_xls.py +676 -0
- unifyxl-0.1.0/src/unifyxl/_xlsx.py +680 -0
- unifyxl-0.1.0/src/unifyxl/exceptions.py +49 -0
- unifyxl-0.1.0/src/unifyxl/py.typed +0 -0
- unifyxl-0.1.0/src/unifyxl/styles.py +545 -0
- unifyxl-0.1.0/src/unifyxl/utils.py +264 -0
unifyxl-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 skrtk98
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
unifyxl-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: unifyxl
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: One API for xlsx (openpyxl) and xls (xlrd + xlwt), including cell formatting and merged cells
|
|
5
|
+
Keywords: excel,xlsx,xls,openpyxl,xlrd,xlwt,spreadsheet
|
|
6
|
+
Author: skrtk98
|
|
7
|
+
License-Expression: MIT
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Classifier: Development Status :: 3 - Alpha
|
|
10
|
+
Classifier: Intended Audience :: Developers
|
|
11
|
+
Classifier: Operating System :: OS Independent
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
14
|
+
Classifier: Topic :: Office/Business :: Financial :: Spreadsheet
|
|
15
|
+
Classifier: Typing :: Typed
|
|
16
|
+
Requires-Dist: openpyxl>=3.1.5
|
|
17
|
+
Requires-Dist: xlrd>=2.0.2
|
|
18
|
+
Requires-Dist: xlwt>=1.3.0
|
|
19
|
+
Requires-Python: >=3.14
|
|
20
|
+
Project-URL: Homepage, https://github.com/skrtk98/unifyxl
|
|
21
|
+
Project-URL: Documentation, https://skrtk98.github.io/unifyxl/
|
|
22
|
+
Project-URL: Repository, https://github.com/skrtk98/unifyxl
|
|
23
|
+
Project-URL: Issues, https://github.com/skrtk98/unifyxl/issues
|
|
24
|
+
Project-URL: Wiki, https://github.com/skrtk98/unifyxl/wiki
|
|
25
|
+
Description-Content-Type: text/markdown
|
|
26
|
+
|
|
27
|
+
# unifyxl
|
|
28
|
+
|
|
29
|
+
English | [日本語](https://github.com/skrtk98/unifyxl/blob/main/README.ja.md)
|
|
30
|
+
|
|
31
|
+
A wrapper library that handles xlsx (openpyxl) and xls (xlrd + xlwt) through the same API.
|
|
32
|
+
Unlike pandas, it reads and writes more than just values:
|
|
33
|
+
|
|
34
|
+
- Formatting: fonts, background colors (fills), borders, alignment, number formats
|
|
35
|
+
- Merged cells
|
|
36
|
+
- Column widths, row heights, freeze panes
|
|
37
|
+
|
|
38
|
+
## Installation
|
|
39
|
+
|
|
40
|
+
```sh
|
|
41
|
+
uv add unifyxl # or: pip install unifyxl
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
Requires Python 3.14 or later. Dependencies: openpyxl, xlrd, xlwt. To install the latest development version, use `uv add git+https://github.com/skrtk98/unifyxl`.
|
|
45
|
+
|
|
46
|
+
## Usage
|
|
47
|
+
|
|
48
|
+
```python
|
|
49
|
+
import unifyxl
|
|
50
|
+
from unifyxl import Alignment, Border, Fill, Font, Side
|
|
51
|
+
|
|
52
|
+
# Load (the format is detected from the content, not the extension)
|
|
53
|
+
wb = unifyxl.load_workbook("input.xls") # same for .xlsx / .xlsm
|
|
54
|
+
ws = wb.active # or wb["Sheet1"], wb[0]
|
|
55
|
+
|
|
56
|
+
cell = ws["B2"] # or ws.cell(2, 2), ws[2, 2]
|
|
57
|
+
cell.value # value
|
|
58
|
+
cell.bg_color # background Color (solid fills only; None otherwise)
|
|
59
|
+
cell.bg_color.rgb # "RRGGBB"
|
|
60
|
+
cell.font.bold, cell.font.color # font
|
|
61
|
+
cell.border.bottom.style # "thin", etc.
|
|
62
|
+
cell.alignment.horizontal # "center", etc.
|
|
63
|
+
cell.number_format # "#,##0", etc.
|
|
64
|
+
cell.merged_range # merged range as CellRange, or None
|
|
65
|
+
ws.merged_ranges # all merged ranges in the sheet
|
|
66
|
+
|
|
67
|
+
# Write
|
|
68
|
+
ws["A1"] = "Header"
|
|
69
|
+
ws["A1"].font = Font(bold=True, size=14, color="FFFFFF")
|
|
70
|
+
ws["A1"].bg_color = "4472C4"
|
|
71
|
+
ws["A1"].border = Border.all("thin", "000000")
|
|
72
|
+
ws["A1"].alignment = Alignment(horizontal="center", vertical="center")
|
|
73
|
+
ws.merge_cells("A1:D1")
|
|
74
|
+
ws.set_column_width("A", 20)
|
|
75
|
+
ws.set_row_height(1, 30)
|
|
76
|
+
ws.freeze_panes = "A2"
|
|
77
|
+
|
|
78
|
+
# Change only part of a style (style objects are immutable; replace() makes a new one)
|
|
79
|
+
ws["B2"].font = ws["B2"].font.replace(italic=True)
|
|
80
|
+
|
|
81
|
+
# Copy another cell's whole style (works across formats too)
|
|
82
|
+
ws["C3"].style = ws["A1"].style
|
|
83
|
+
|
|
84
|
+
wb.save("output.xls")
|
|
85
|
+
wb.save("output.xlsx") # a different extension converts on save
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
Create a new workbook with `unifyxl.new_workbook("xlsx")` or `unifyxl.new_workbook("xls")`.
|
|
89
|
+
|
|
90
|
+
## API overview
|
|
91
|
+
|
|
92
|
+
| Object | Main API |
|
|
93
|
+
|---|---|
|
|
94
|
+
| Workbook | `sheetnames`, `worksheets`, `active`, `create_sheet()`, `remove_sheet()`, `del wb[name]`, `save()`, `convert()`, `format`, `theme_colors`, `theme_color()` |
|
|
95
|
+
| 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` |
|
|
96
|
+
| Cell | `value`, `style`, `font`, `fill`, `border`, `alignment`, `number_format`, `bg_color`, `merged_range`, `is_merged`, `is_formula`, `coordinate` |
|
|
97
|
+
| 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)`) |
|
|
98
|
+
|
|
99
|
+
- Row and column numbers are 1-based. Columns can be given as `"A"` or `1`.
|
|
100
|
+
- Colors are returned as `Color` objects; `color.rgb` is the `"RRGGBB"` value. `None` means "automatic".
|
|
101
|
+
- When setting a color, besides `Color` you can pass `"RRGGBB"`, `"#rrggbb"`, `"AARRGGBB"` or `(r, g, b)`; it is converted to a `Color`.
|
|
102
|
+
- `==` 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"`.
|
|
103
|
+
- 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).
|
|
104
|
+
- 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.
|
|
105
|
+
- To specify a theme color, use `wb.theme_color(4, tint=0.4)`. Indexes follow `THEME_COLOR_NAMES` (0: lt1, 1: dk1, 2: lt2, 3: dk2, 4-9: accent1-6, 10: hlink, 11: folHlink). 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).
|
|
106
|
+
- 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)`).
|
|
107
|
+
- Rows range from 1 to 1048576 and columns from 1 to 16384 (A to XFD). Out-of-range values raise `ValueError`.
|
|
108
|
+
- Writing a value to a merged cell other than the top-left one raises `MergedCellError`.
|
|
109
|
+
- 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).
|
|
110
|
+
- 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).
|
|
111
|
+
- If you need the underlying objects, use `wb.openpyxl_workbook` and `ws.openpyxl_worksheet` (xlsx only).
|
|
112
|
+
|
|
113
|
+
## Format differences and limitations
|
|
114
|
+
|
|
115
|
+
### xlsx (openpyxl)
|
|
116
|
+
- 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.
|
|
117
|
+
- Because the openpyxl objects are wrapped directly, parts you don't touch (comments, data validation, etc.) are saved as far as openpyxl preserves them.
|
|
118
|
+
- 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.
|
|
119
|
+
- 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 = ...`).
|
|
120
|
+
- Gradient fills cannot be read (they are returned as no fill).
|
|
121
|
+
- The theme itself (its color definitions) is read-only and cannot be changed.
|
|
122
|
+
- 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.
|
|
123
|
+
- 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.
|
|
124
|
+
|
|
125
|
+
### xls (xlrd + xlwt)
|
|
126
|
+
- 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.**
|
|
127
|
+
- 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.
|
|
128
|
+
- 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.
|
|
129
|
+
- The limits are 65536 rows × 256 columns and 4000 distinct cell formats. Exceeding them raises `FormatLimitError`, also when converting from xlsx to xls.
|
|
130
|
+
- Indentation is limited to 15 (larger values are clipped to 15).
|
|
131
|
+
- Integral numbers are returned as `int` (to match xlsx results).
|
|
132
|
+
- 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.
|
|
133
|
+
- 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.
|
|
134
|
+
|
|
135
|
+
### Both formats
|
|
136
|
+
- 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`.
|
|
137
|
+
- 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).
|
|
138
|
+
- 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.
|
|
139
|
+
- Inserting or deleting rows and columns, diagonal borders, cell protection and hyperlinks are not supported.
|
|
140
|
+
|
|
141
|
+
## License
|
|
142
|
+
|
|
143
|
+
MIT License. See [LICENSE](https://github.com/skrtk98/unifyxl/blob/main/LICENSE).
|
|
144
|
+
|
|
145
|
+
## Development
|
|
146
|
+
|
|
147
|
+
```sh
|
|
148
|
+
uv sync
|
|
149
|
+
uv run pytest
|
|
150
|
+
```
|
unifyxl-0.1.0/README.md
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
# unifyxl
|
|
2
|
+
|
|
3
|
+
English | [日本語](https://github.com/skrtk98/unifyxl/blob/main/README.ja.md)
|
|
4
|
+
|
|
5
|
+
A wrapper library that handles xlsx (openpyxl) and xls (xlrd + xlwt) through the same API.
|
|
6
|
+
Unlike pandas, it reads and writes more than just values:
|
|
7
|
+
|
|
8
|
+
- Formatting: fonts, background colors (fills), borders, alignment, number formats
|
|
9
|
+
- Merged cells
|
|
10
|
+
- Column widths, row heights, freeze panes
|
|
11
|
+
|
|
12
|
+
## Installation
|
|
13
|
+
|
|
14
|
+
```sh
|
|
15
|
+
uv add unifyxl # or: pip install unifyxl
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
Requires Python 3.14 or later. Dependencies: openpyxl, xlrd, xlwt. To install the latest development version, use `uv add git+https://github.com/skrtk98/unifyxl`.
|
|
19
|
+
|
|
20
|
+
## Usage
|
|
21
|
+
|
|
22
|
+
```python
|
|
23
|
+
import unifyxl
|
|
24
|
+
from unifyxl import Alignment, Border, Fill, Font, Side
|
|
25
|
+
|
|
26
|
+
# Load (the format is detected from the content, not the extension)
|
|
27
|
+
wb = unifyxl.load_workbook("input.xls") # same for .xlsx / .xlsm
|
|
28
|
+
ws = wb.active # or wb["Sheet1"], wb[0]
|
|
29
|
+
|
|
30
|
+
cell = ws["B2"] # or ws.cell(2, 2), ws[2, 2]
|
|
31
|
+
cell.value # value
|
|
32
|
+
cell.bg_color # background Color (solid fills only; None otherwise)
|
|
33
|
+
cell.bg_color.rgb # "RRGGBB"
|
|
34
|
+
cell.font.bold, cell.font.color # font
|
|
35
|
+
cell.border.bottom.style # "thin", etc.
|
|
36
|
+
cell.alignment.horizontal # "center", etc.
|
|
37
|
+
cell.number_format # "#,##0", etc.
|
|
38
|
+
cell.merged_range # merged range as CellRange, or None
|
|
39
|
+
ws.merged_ranges # all merged ranges in the sheet
|
|
40
|
+
|
|
41
|
+
# Write
|
|
42
|
+
ws["A1"] = "Header"
|
|
43
|
+
ws["A1"].font = Font(bold=True, size=14, color="FFFFFF")
|
|
44
|
+
ws["A1"].bg_color = "4472C4"
|
|
45
|
+
ws["A1"].border = Border.all("thin", "000000")
|
|
46
|
+
ws["A1"].alignment = Alignment(horizontal="center", vertical="center")
|
|
47
|
+
ws.merge_cells("A1:D1")
|
|
48
|
+
ws.set_column_width("A", 20)
|
|
49
|
+
ws.set_row_height(1, 30)
|
|
50
|
+
ws.freeze_panes = "A2"
|
|
51
|
+
|
|
52
|
+
# Change only part of a style (style objects are immutable; replace() makes a new one)
|
|
53
|
+
ws["B2"].font = ws["B2"].font.replace(italic=True)
|
|
54
|
+
|
|
55
|
+
# Copy another cell's whole style (works across formats too)
|
|
56
|
+
ws["C3"].style = ws["A1"].style
|
|
57
|
+
|
|
58
|
+
wb.save("output.xls")
|
|
59
|
+
wb.save("output.xlsx") # a different extension converts on save
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
Create a new workbook with `unifyxl.new_workbook("xlsx")` or `unifyxl.new_workbook("xls")`.
|
|
63
|
+
|
|
64
|
+
## API overview
|
|
65
|
+
|
|
66
|
+
| Object | Main API |
|
|
67
|
+
|---|---|
|
|
68
|
+
| Workbook | `sheetnames`, `worksheets`, `active`, `create_sheet()`, `remove_sheet()`, `del wb[name]`, `save()`, `convert()`, `format`, `theme_colors`, `theme_color()` |
|
|
69
|
+
| 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` |
|
|
70
|
+
| Cell | `value`, `style`, `font`, `fill`, `border`, `alignment`, `number_format`, `bg_color`, `merged_range`, `is_merged`, `is_formula`, `coordinate` |
|
|
71
|
+
| 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)`) |
|
|
72
|
+
|
|
73
|
+
- Row and column numbers are 1-based. Columns can be given as `"A"` or `1`.
|
|
74
|
+
- Colors are returned as `Color` objects; `color.rgb` is the `"RRGGBB"` value. `None` means "automatic".
|
|
75
|
+
- When setting a color, besides `Color` you can pass `"RRGGBB"`, `"#rrggbb"`, `"AARRGGBB"` or `(r, g, b)`; it is converted to a `Color`.
|
|
76
|
+
- `==` 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"`.
|
|
77
|
+
- 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).
|
|
78
|
+
- 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.
|
|
79
|
+
- To specify a theme color, use `wb.theme_color(4, tint=0.4)`. Indexes follow `THEME_COLOR_NAMES` (0: lt1, 1: dk1, 2: lt2, 3: dk2, 4-9: accent1-6, 10: hlink, 11: folHlink). 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).
|
|
80
|
+
- 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)`).
|
|
81
|
+
- Rows range from 1 to 1048576 and columns from 1 to 16384 (A to XFD). Out-of-range values raise `ValueError`.
|
|
82
|
+
- Writing a value to a merged cell other than the top-left one raises `MergedCellError`.
|
|
83
|
+
- 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).
|
|
84
|
+
- 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).
|
|
85
|
+
- If you need the underlying objects, use `wb.openpyxl_workbook` and `ws.openpyxl_worksheet` (xlsx only).
|
|
86
|
+
|
|
87
|
+
## Format differences and limitations
|
|
88
|
+
|
|
89
|
+
### xlsx (openpyxl)
|
|
90
|
+
- 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.
|
|
91
|
+
- Because the openpyxl objects are wrapped directly, parts you don't touch (comments, data validation, etc.) are saved as far as openpyxl preserves them.
|
|
92
|
+
- 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.
|
|
93
|
+
- 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 = ...`).
|
|
94
|
+
- Gradient fills cannot be read (they are returned as no fill).
|
|
95
|
+
- The theme itself (its color definitions) is read-only and cannot be changed.
|
|
96
|
+
- 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.
|
|
97
|
+
- 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.
|
|
98
|
+
|
|
99
|
+
### xls (xlrd + xlwt)
|
|
100
|
+
- 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.**
|
|
101
|
+
- 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.
|
|
102
|
+
- 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.
|
|
103
|
+
- The limits are 65536 rows × 256 columns and 4000 distinct cell formats. Exceeding them raises `FormatLimitError`, also when converting from xlsx to xls.
|
|
104
|
+
- Indentation is limited to 15 (larger values are clipped to 15).
|
|
105
|
+
- Integral numbers are returned as `int` (to match xlsx results).
|
|
106
|
+
- 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.
|
|
107
|
+
- 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.
|
|
108
|
+
|
|
109
|
+
### Both formats
|
|
110
|
+
- 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`.
|
|
111
|
+
- 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).
|
|
112
|
+
- 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.
|
|
113
|
+
- Inserting or deleting rows and columns, diagonal borders, cell protection and hyperlinks are not supported.
|
|
114
|
+
|
|
115
|
+
## License
|
|
116
|
+
|
|
117
|
+
MIT License. See [LICENSE](https://github.com/skrtk98/unifyxl/blob/main/LICENSE).
|
|
118
|
+
|
|
119
|
+
## Development
|
|
120
|
+
|
|
121
|
+
```sh
|
|
122
|
+
uv sync
|
|
123
|
+
uv run pytest
|
|
124
|
+
```
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "unifyxl"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "One API for xlsx (openpyxl) and xls (xlrd + xlwt), including cell formatting and merged cells"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
requires-python = ">=3.14"
|
|
7
|
+
license = "MIT"
|
|
8
|
+
license-files = ["LICENSE"]
|
|
9
|
+
keywords = [
|
|
10
|
+
"excel",
|
|
11
|
+
"xlsx",
|
|
12
|
+
"xls",
|
|
13
|
+
"openpyxl",
|
|
14
|
+
"xlrd",
|
|
15
|
+
"xlwt",
|
|
16
|
+
"spreadsheet",
|
|
17
|
+
]
|
|
18
|
+
classifiers = [
|
|
19
|
+
"Development Status :: 3 - Alpha",
|
|
20
|
+
"Intended Audience :: Developers",
|
|
21
|
+
"Operating System :: OS Independent",
|
|
22
|
+
"Programming Language :: Python :: 3",
|
|
23
|
+
"Programming Language :: Python :: 3.14",
|
|
24
|
+
"Topic :: Office/Business :: Financial :: Spreadsheet",
|
|
25
|
+
"Typing :: Typed",
|
|
26
|
+
]
|
|
27
|
+
dependencies = [
|
|
28
|
+
"openpyxl>=3.1.5",
|
|
29
|
+
"xlrd>=2.0.2",
|
|
30
|
+
"xlwt>=1.3.0",
|
|
31
|
+
]
|
|
32
|
+
|
|
33
|
+
[[project.authors]]
|
|
34
|
+
name = "skrtk98"
|
|
35
|
+
|
|
36
|
+
[project.urls]
|
|
37
|
+
Homepage = "https://github.com/skrtk98/unifyxl"
|
|
38
|
+
Documentation = "https://skrtk98.github.io/unifyxl/"
|
|
39
|
+
Repository = "https://github.com/skrtk98/unifyxl"
|
|
40
|
+
Issues = "https://github.com/skrtk98/unifyxl/issues"
|
|
41
|
+
Wiki = "https://github.com/skrtk98/unifyxl/wiki"
|
|
42
|
+
|
|
43
|
+
[build-system]
|
|
44
|
+
requires = ["uv_build>=0.13.1,<0.14.0"]
|
|
45
|
+
build-backend = "uv_build"
|
|
46
|
+
|
|
47
|
+
[dependency-groups]
|
|
48
|
+
dev = ["pytest>=9.2.0"]
|
|
49
|
+
docs = [
|
|
50
|
+
"furo>=2025.12.19",
|
|
51
|
+
"sphinx>=9.2.0",
|
|
52
|
+
]
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "unifyxl"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "One API for xlsx (openpyxl) and xls (xlrd + xlwt), including cell formatting and merged cells"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
requires-python = ">=3.14"
|
|
7
|
+
authors = [{ name = "skrtk98" }]
|
|
8
|
+
license = "MIT"
|
|
9
|
+
license-files = ["LICENSE"]
|
|
10
|
+
keywords = ["excel", "xlsx", "xls", "openpyxl", "xlrd", "xlwt", "spreadsheet"]
|
|
11
|
+
classifiers = [
|
|
12
|
+
"Development Status :: 3 - Alpha",
|
|
13
|
+
"Intended Audience :: Developers",
|
|
14
|
+
"Operating System :: OS Independent",
|
|
15
|
+
"Programming Language :: Python :: 3",
|
|
16
|
+
"Programming Language :: Python :: 3.14",
|
|
17
|
+
"Topic :: Office/Business :: Financial :: Spreadsheet",
|
|
18
|
+
"Typing :: Typed",
|
|
19
|
+
]
|
|
20
|
+
dependencies = [
|
|
21
|
+
"openpyxl>=3.1.5",
|
|
22
|
+
"xlrd>=2.0.2",
|
|
23
|
+
"xlwt>=1.3.0",
|
|
24
|
+
]
|
|
25
|
+
|
|
26
|
+
[project.urls]
|
|
27
|
+
Homepage = "https://github.com/skrtk98/unifyxl"
|
|
28
|
+
Documentation = "https://skrtk98.github.io/unifyxl/"
|
|
29
|
+
Repository = "https://github.com/skrtk98/unifyxl"
|
|
30
|
+
Issues = "https://github.com/skrtk98/unifyxl/issues"
|
|
31
|
+
Wiki = "https://github.com/skrtk98/unifyxl/wiki"
|
|
32
|
+
|
|
33
|
+
[build-system]
|
|
34
|
+
requires = ["uv_build>=0.13.1,<0.14.0"]
|
|
35
|
+
build-backend = "uv_build"
|
|
36
|
+
|
|
37
|
+
[dependency-groups]
|
|
38
|
+
dev = [
|
|
39
|
+
"pytest>=9.2.0",
|
|
40
|
+
]
|
|
41
|
+
docs = [
|
|
42
|
+
"furo>=2025.12.19",
|
|
43
|
+
"sphinx>=9.2.0",
|
|
44
|
+
]
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
"""Read, write, and convert Excel workbooks through one API.
|
|
2
|
+
|
|
3
|
+
The xlsx backend wraps openpyxl and also accepts xlsm files. The xls backend
|
|
4
|
+
uses xlrd for reading and xlwt for writing. Both expose cell values, immutable
|
|
5
|
+
styles, merged ranges, dimensions, and freeze panes through the same interface.
|
|
6
|
+
Rows and columns use 1-based indexes; worksheet positions use 0-based indexes.
|
|
7
|
+
|
|
8
|
+
Example:
|
|
9
|
+
Create a workbook, format a cell, and save it in either format::
|
|
10
|
+
|
|
11
|
+
import unifyxl
|
|
12
|
+
|
|
13
|
+
wb = unifyxl.new_workbook()
|
|
14
|
+
ws = wb.active
|
|
15
|
+
ws["A1"] = "Report"
|
|
16
|
+
ws["A1"].font = ws["A1"].font.replace(bold=True)
|
|
17
|
+
ws["A1"].bg_color = "FFFF00"
|
|
18
|
+
ws.merge_cells("A1:C1")
|
|
19
|
+
wb.save("report.xlsx")
|
|
20
|
+
wb.save("report.xls")
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
import os
|
|
26
|
+
from typing import IO
|
|
27
|
+
|
|
28
|
+
from ._base import Cell, Workbook, Worksheet
|
|
29
|
+
from .exceptions import (
|
|
30
|
+
FormatLimitError,
|
|
31
|
+
MergedCellError,
|
|
32
|
+
UnifyXLError,
|
|
33
|
+
UnsupportedFormatError,
|
|
34
|
+
)
|
|
35
|
+
from .styles import (
|
|
36
|
+
THEME_COLOR_NAMES,
|
|
37
|
+
Alignment,
|
|
38
|
+
Border,
|
|
39
|
+
CellStyle,
|
|
40
|
+
Color,
|
|
41
|
+
ColorLike,
|
|
42
|
+
Fill,
|
|
43
|
+
Font,
|
|
44
|
+
Side,
|
|
45
|
+
normalize_color,
|
|
46
|
+
)
|
|
47
|
+
from .utils import CellRange, column_index, column_letter, coordinate, parse_coordinate
|
|
48
|
+
|
|
49
|
+
__all__ = [
|
|
50
|
+
"THEME_COLOR_NAMES", "Alignment", "Border", "Cell", "CellRange", "CellStyle",
|
|
51
|
+
"Color", "ColorLike", "Fill", "Font",
|
|
52
|
+
"FormatLimitError", "MergedCellError", "Side", "UnifyXLError",
|
|
53
|
+
"UnsupportedFormatError", "Workbook", "Worksheet", "column_index",
|
|
54
|
+
"column_letter", "coordinate", "detect_format", "load_workbook",
|
|
55
|
+
"new_workbook", "normalize_color", "parse_coordinate",
|
|
56
|
+
]
|
|
57
|
+
|
|
58
|
+
_OLE2_MAGIC = b"\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1"
|
|
59
|
+
_ZIP_MAGIC = b"PK\x03\x04"
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def detect_format(source: str | os.PathLike | IO[bytes]) -> str:
|
|
63
|
+
"""Detect an Excel container format from its contents.
|
|
64
|
+
|
|
65
|
+
ZIP and OLE2 signatures identify xlsx and xls containers, respectively; this
|
|
66
|
+
does not validate the workbook inside the container. A stream's position is
|
|
67
|
+
restored after reading the signature.
|
|
68
|
+
|
|
69
|
+
Args:
|
|
70
|
+
source: A filesystem path or a seekable binary stream. Streams are
|
|
71
|
+
inspected at their current position and remain open.
|
|
72
|
+
|
|
73
|
+
Returns:
|
|
74
|
+
The string ``"xlsx"`` or ``"xls"``. An xlsm container returns ``"xlsx"``.
|
|
75
|
+
|
|
76
|
+
Raises:
|
|
77
|
+
UnsupportedFormatError: The signature matches neither supported format.
|
|
78
|
+
OSError: The path cannot be opened or the source cannot be read or sought.
|
|
79
|
+
"""
|
|
80
|
+
if isinstance(source, (str, os.PathLike)):
|
|
81
|
+
with open(source, "rb") as f:
|
|
82
|
+
head = f.read(8)
|
|
83
|
+
else:
|
|
84
|
+
pos = source.tell()
|
|
85
|
+
head = source.read(8)
|
|
86
|
+
source.seek(pos)
|
|
87
|
+
if head.startswith(_ZIP_MAGIC):
|
|
88
|
+
return "xlsx"
|
|
89
|
+
if head == _OLE2_MAGIC:
|
|
90
|
+
return "xls"
|
|
91
|
+
raise UnsupportedFormatError("not an xlsx or xls file")
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def load_workbook(
|
|
95
|
+
source: str | os.PathLike | IO[bytes],
|
|
96
|
+
*,
|
|
97
|
+
data_only: bool = False,
|
|
98
|
+
) -> Workbook:
|
|
99
|
+
"""Load an xlsx, xlsm, or xls workbook detected by its contents.
|
|
100
|
+
|
|
101
|
+
No formula calculation is performed. The xlsx backend preserves features
|
|
102
|
+
supported by openpyxl, including embedded VBA when present. The xls backend
|
|
103
|
+
loads the common model into memory; features outside that model are lost
|
|
104
|
+
when saving, including charts, images, comments, and data validation.
|
|
105
|
+
|
|
106
|
+
Args:
|
|
107
|
+
source: A filesystem path or seekable binary stream containing the
|
|
108
|
+
workbook at its current position. A supplied stream remains open,
|
|
109
|
+
but loading consumes its contents.
|
|
110
|
+
data_only: For xlsx, return cached formula results instead of formula
|
|
111
|
+
strings. Defaults to ``False``. Ignored for xls, which always reads
|
|
112
|
+
cached results because xlrd cannot read formulas.
|
|
113
|
+
|
|
114
|
+
Returns:
|
|
115
|
+
A format-specific implementation of :class:`Workbook`.
|
|
116
|
+
|
|
117
|
+
Raises:
|
|
118
|
+
UnsupportedFormatError: The source has neither a ZIP nor OLE2 signature.
|
|
119
|
+
OSError: The source cannot be opened or read.
|
|
120
|
+
|
|
121
|
+
Example:
|
|
122
|
+
Read the active sheet's values::
|
|
123
|
+
|
|
124
|
+
wb = load_workbook("report.xlsx", data_only=True)
|
|
125
|
+
rows = wb.active.values()
|
|
126
|
+
"""
|
|
127
|
+
fmt = detect_format(source)
|
|
128
|
+
if fmt == "xlsx":
|
|
129
|
+
from ._xlsx import XlsxWorkbook
|
|
130
|
+
|
|
131
|
+
return XlsxWorkbook.load(source, data_only=data_only)
|
|
132
|
+
from ._xls import XlsWorkbook
|
|
133
|
+
|
|
134
|
+
return XlsWorkbook.load(source)
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def new_workbook(format: str = "xlsx", *, _empty: bool = False) -> Workbook:
|
|
138
|
+
"""Create a workbook with one worksheet named ``"Sheet"`` by default.
|
|
139
|
+
|
|
140
|
+
Args:
|
|
141
|
+
format: Output model, either ``"xlsx"`` (the default) or ``"xls"``.
|
|
142
|
+
_empty: Internal conversion option. If ``True``, create no worksheets;
|
|
143
|
+
at least one worksheet must be added before saving. Defaults to
|
|
144
|
+
``False``.
|
|
145
|
+
|
|
146
|
+
Returns:
|
|
147
|
+
A new format-specific :class:`Workbook` with no associated source path.
|
|
148
|
+
|
|
149
|
+
Raises:
|
|
150
|
+
ValueError: ``format`` is neither ``"xlsx"`` nor ``"xls"``.
|
|
151
|
+
"""
|
|
152
|
+
if format == "xlsx":
|
|
153
|
+
from ._xlsx import XlsxWorkbook
|
|
154
|
+
|
|
155
|
+
return XlsxWorkbook.new(with_sheet=not _empty)
|
|
156
|
+
if format == "xls":
|
|
157
|
+
from ._xls import XlsWorkbook
|
|
158
|
+
|
|
159
|
+
return XlsWorkbook.new(with_sheet=not _empty)
|
|
160
|
+
raise ValueError(f"unknown format: {format!r} (expected 'xlsx' or 'xls')")
|