urban-json-excel 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.
- urban_json_excel-0.1.0/LICENSE +21 -0
- urban_json_excel-0.1.0/PKG-INFO +53 -0
- urban_json_excel-0.1.0/README.md +23 -0
- urban_json_excel-0.1.0/pyproject.toml +62 -0
- urban_json_excel-0.1.0/setup.cfg +4 -0
- urban_json_excel-0.1.0/src/urban_json_excel/__init__.py +299 -0
- urban_json_excel-0.1.0/src/urban_json_excel/py.typed +0 -0
- urban_json_excel-0.1.0/src/urban_json_excel.egg-info/PKG-INFO +53 -0
- urban_json_excel-0.1.0/src/urban_json_excel.egg-info/SOURCES.txt +12 -0
- urban_json_excel-0.1.0/src/urban_json_excel.egg-info/dependency_links.txt +1 -0
- urban_json_excel-0.1.0/src/urban_json_excel.egg-info/entry_points.txt +2 -0
- urban_json_excel-0.1.0/src/urban_json_excel.egg-info/requires.txt +5 -0
- urban_json_excel-0.1.0/src/urban_json_excel.egg-info/top_level.txt +1 -0
- urban_json_excel-0.1.0/tests/test_excel.py +197 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 black beard
|
|
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.
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: urban-json-excel
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Plugin urban-json : lecture de classeurs Excel (loadxls, loadxlssheet).
|
|
5
|
+
Author-email: Gael Beard <gaelgael5@gmail.com>
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://github.com/gaelgael5/Jslt
|
|
8
|
+
Project-URL: Repository, https://github.com/gaelgael5/Jslt
|
|
9
|
+
Keywords: json,transform,template,jslt,excel,plugin
|
|
10
|
+
Classifier: Development Status :: 3 - Alpha
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
19
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
20
|
+
Classifier: Topic :: Text Processing :: Markup
|
|
21
|
+
Classifier: Typing :: Typed
|
|
22
|
+
Requires-Python: >=3.9
|
|
23
|
+
Description-Content-Type: text/markdown
|
|
24
|
+
License-File: LICENSE
|
|
25
|
+
Requires-Dist: urban-json
|
|
26
|
+
Requires-Dist: openpyxl>=3.1
|
|
27
|
+
Provides-Extra: xls
|
|
28
|
+
Requires-Dist: xlrd>=2.0; extra == "xls"
|
|
29
|
+
Dynamic: license-file
|
|
30
|
+
|
|
31
|
+
# urban-json-excel
|
|
32
|
+
|
|
33
|
+
Plugin [urban-json](https://github.com/gaelgael5/Jslt) : **classeurs Excel** dans les
|
|
34
|
+
templates (port de `ServicesXls` / `ExcelReader`, .NET).
|
|
35
|
+
|
|
36
|
+
```bash
|
|
37
|
+
pip install urban-json-excel # .xlsx (openpyxl)
|
|
38
|
+
pip install "urban-json-excel[xls]" # + anciens .xls (xlrd)
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
- `loadxls(classeur, "config.json")` — configuration lue dans un fichier JSON ;
|
|
42
|
+
- `loadxlssheet(classeur, { … })` — configuration passée en objet.
|
|
43
|
+
|
|
44
|
+
```json
|
|
45
|
+
{ "FirstRowHasColumnName": true, "HeaderLine": 0, "Tablename": "Feuil1",
|
|
46
|
+
"AddRowNumber": true, "ByPassEmptyObject": true,
|
|
47
|
+
"Columns": [ { "Index": 0, "Name": "id", "Type": "integer", "Trimmed": true, "BypassEmptyValue": true } ] }
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
Chaque ligne devient un objet (`"$row"` = rang de la ligne de données si
|
|
51
|
+
`AddRowNumber`). Sans `Columns`, toutes les colonnes sont lues, noms assainis
|
|
52
|
+
(`"Nom complet"` → `Nom_complet`) et colonnes entièrement entières typées `integer`.
|
|
53
|
+
Si `Tablename` est vide, la feuille unique du classeur est prise.
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
# urban-json-excel
|
|
2
|
+
|
|
3
|
+
Plugin [urban-json](https://github.com/gaelgael5/Jslt) : **classeurs Excel** dans les
|
|
4
|
+
templates (port de `ServicesXls` / `ExcelReader`, .NET).
|
|
5
|
+
|
|
6
|
+
```bash
|
|
7
|
+
pip install urban-json-excel # .xlsx (openpyxl)
|
|
8
|
+
pip install "urban-json-excel[xls]" # + anciens .xls (xlrd)
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
- `loadxls(classeur, "config.json")` — configuration lue dans un fichier JSON ;
|
|
12
|
+
- `loadxlssheet(classeur, { … })` — configuration passée en objet.
|
|
13
|
+
|
|
14
|
+
```json
|
|
15
|
+
{ "FirstRowHasColumnName": true, "HeaderLine": 0, "Tablename": "Feuil1",
|
|
16
|
+
"AddRowNumber": true, "ByPassEmptyObject": true,
|
|
17
|
+
"Columns": [ { "Index": 0, "Name": "id", "Type": "integer", "Trimmed": true, "BypassEmptyValue": true } ] }
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
Chaque ligne devient un objet (`"$row"` = rang de la ligne de données si
|
|
21
|
+
`AddRowNumber`). Sans `Columns`, toutes les colonnes sont lues, noms assainis
|
|
22
|
+
(`"Nom complet"` → `Nom_complet`) et colonnes entièrement entières typées `integer`.
|
|
23
|
+
Si `Tablename` est vide, la feuille unique du classeur est prise.
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=77", "wheel"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "urban-json-excel"
|
|
7
|
+
dynamic = ["version"]
|
|
8
|
+
description = "Plugin urban-json : lecture de classeurs Excel (loadxls, loadxlssheet)."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.9"
|
|
11
|
+
license = "Apache-2.0"
|
|
12
|
+
license-files = ["LICENSE"]
|
|
13
|
+
authors = [{ name = "Gael Beard", email = "gaelgael5@gmail.com" }]
|
|
14
|
+
keywords = ["json", "transform", "template", "jslt", "excel", "plugin"]
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Development Status :: 3 - Alpha",
|
|
17
|
+
"Intended Audience :: Developers",
|
|
18
|
+
"Operating System :: OS Independent",
|
|
19
|
+
"Programming Language :: Python :: 3",
|
|
20
|
+
"Programming Language :: Python :: 3.9",
|
|
21
|
+
"Programming Language :: Python :: 3.10",
|
|
22
|
+
"Programming Language :: Python :: 3.11",
|
|
23
|
+
"Programming Language :: Python :: 3.12",
|
|
24
|
+
"Programming Language :: Python :: 3.13",
|
|
25
|
+
"Topic :: Software Development :: Libraries :: Python Modules",
|
|
26
|
+
"Topic :: Text Processing :: Markup",
|
|
27
|
+
"Typing :: Typed",
|
|
28
|
+
]
|
|
29
|
+
dependencies = [
|
|
30
|
+
"urban-json",
|
|
31
|
+
# Classeurs .xlsx (ExcelDataReader côté .NET).
|
|
32
|
+
"openpyxl>=3.1",
|
|
33
|
+
]
|
|
34
|
+
|
|
35
|
+
[project.optional-dependencies]
|
|
36
|
+
# Anciens classeurs .xls (format binaire Excel 97-2003).
|
|
37
|
+
xls = ["xlrd>=2.0"]
|
|
38
|
+
|
|
39
|
+
[project.urls]
|
|
40
|
+
Homepage = "https://github.com/gaelgael5/Jslt"
|
|
41
|
+
Repository = "https://github.com/gaelgael5/Jslt"
|
|
42
|
+
|
|
43
|
+
# Découverte automatique par urban-json : installer ce paquet suffit à exposer ses fonctions.
|
|
44
|
+
[project.entry-points."urban_json.functions"]
|
|
45
|
+
excel = "urban_json_excel:register"
|
|
46
|
+
|
|
47
|
+
[tool.setuptools.dynamic]
|
|
48
|
+
version = { attr = "urban_json_excel.__version__" }
|
|
49
|
+
|
|
50
|
+
[tool.setuptools.packages.find]
|
|
51
|
+
where = ["src"]
|
|
52
|
+
|
|
53
|
+
[tool.setuptools.package-data]
|
|
54
|
+
urban_json_excel = ["py.typed"]
|
|
55
|
+
|
|
56
|
+
[tool.pytest.ini_options]
|
|
57
|
+
testpaths = ["tests"]
|
|
58
|
+
pythonpath = ["src"]
|
|
59
|
+
|
|
60
|
+
[tool.ruff]
|
|
61
|
+
line-length = 100
|
|
62
|
+
src = ["src", "tests"]
|
|
@@ -0,0 +1,299 @@
|
|
|
1
|
+
"""Plugin urban-json : lecture de classeurs Excel (``loadxls``, ``loadxlssheet``).
|
|
2
|
+
|
|
3
|
+
Port de ``ServicesXls`` + ``ExcelReader`` (.NET, ExcelDataReader). ``.xlsx`` via
|
|
4
|
+
openpyxl ; ``.xls`` (Excel 97-2003) via xlrd, avec l'extra ``urban-json-excel[xls]``.
|
|
5
|
+
|
|
6
|
+
* ``loadxls(fichier, fichier_de_configuration)`` — configuration lue dans un
|
|
7
|
+
fichier JSON ;
|
|
8
|
+
* ``loadxlssheet(fichier, configuration)`` — configuration passée en objet.
|
|
9
|
+
|
|
10
|
+
Configuration (clés insensibles à la casse, comme la désérialisation .NET) ::
|
|
11
|
+
|
|
12
|
+
{ "FirstRowHasColumnName": true, // 1re ligne = noms de colonnes
|
|
13
|
+
"HeaderLine": 0, // > 0 : ligne d'en-tête (données après elle)
|
|
14
|
+
"Tablename": "Feuil1", // feuille ; vide = l'unique feuille
|
|
15
|
+
"AddRowNumber": true, // ajoute "$row" (rang de la ligne de données)
|
|
16
|
+
"ByPassEmptyObject": true, // omet les lignes sans aucune valeur
|
|
17
|
+
"Columns": [ { "Index": 0, "Name": "id", "Type": "integer",
|
|
18
|
+
"Trimmed": true, "BypassEmptyValue": true } ] }
|
|
19
|
+
|
|
20
|
+
Sans ``Columns`` : toutes les colonnes, noms assainis (accents retirés, espaces ->
|
|
21
|
+
``_``, doublons suffixés ``_renamed_<index>``), colonne numérique entièrement
|
|
22
|
+
entière typée ``integer``. Avec ``Columns`` : seules ces colonnes, typées.
|
|
23
|
+
|
|
24
|
+
Écarts volontaires vs .NET : feuille unique prise quand ``Tablename`` est vide (le
|
|
25
|
+
.NET échouait toujours, son test « table manquante » précédant ce cas) ; dates en
|
|
26
|
+
ISO 8601 ; erreurs explicites (``JsltError``). Chemins relatifs au répertoire
|
|
27
|
+
courant (pas de ``ResolveFile``).
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
from __future__ import annotations
|
|
31
|
+
|
|
32
|
+
import json
|
|
33
|
+
import os
|
|
34
|
+
import unicodedata
|
|
35
|
+
from dataclasses import dataclass
|
|
36
|
+
from datetime import date, datetime, time
|
|
37
|
+
from typing import Any
|
|
38
|
+
|
|
39
|
+
from urban_json import JsltError
|
|
40
|
+
|
|
41
|
+
__version__ = "0.1.0"
|
|
42
|
+
|
|
43
|
+
__all__ = ["execute_loadxls", "execute_loadxlssheet", "register"]
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
# --- configuration ------------------------------------------------------------------
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _get(config: dict, key: str, default: Any = None) -> Any:
|
|
50
|
+
lowered = key.lower()
|
|
51
|
+
for name, value in config.items():
|
|
52
|
+
if str(name).lower() == lowered:
|
|
53
|
+
return value
|
|
54
|
+
return default
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
@dataclass
|
|
58
|
+
class _Column:
|
|
59
|
+
index: int
|
|
60
|
+
name: str
|
|
61
|
+
type: str = "string"
|
|
62
|
+
trimmed: bool = True
|
|
63
|
+
bypass_empty: bool = True
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
_TYPE_ALIASES = {
|
|
67
|
+
"string": "string", "system.string": "string", "text": "string",
|
|
68
|
+
"integer": "integer", "int": "integer", "long": "integer", "int32": "integer", "int64": "integer",
|
|
69
|
+
"system.int32": "integer", "system.int64": "integer",
|
|
70
|
+
"decimal": "number", "double": "number", "float": "number", "number": "number",
|
|
71
|
+
"system.double": "number", "system.decimal": "number", "system.single": "number",
|
|
72
|
+
"boolean": "boolean", "bool": "boolean", "system.boolean": "boolean",
|
|
73
|
+
"datetime": "datetime", "date": "datetime", "system.datetime": "datetime",
|
|
74
|
+
"auto": "auto",
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _columns_from_config(config: dict) -> list[_Column] | None:
|
|
79
|
+
raw = _get(config, "Columns")
|
|
80
|
+
if not raw:
|
|
81
|
+
return None
|
|
82
|
+
columns = []
|
|
83
|
+
for item in raw:
|
|
84
|
+
if not isinstance(item, dict) or _get(item, "Index") is None or not _get(item, "Name"):
|
|
85
|
+
raise JsltError(f"loadxls : colonne de configuration invalide {item!r} (Index et Name requis)")
|
|
86
|
+
type_name = str(_get(item, "Type", "string")).strip().lower()
|
|
87
|
+
if type_name not in _TYPE_ALIASES:
|
|
88
|
+
raise JsltError(f"loadxls : type de colonne inconnu {type_name!r}")
|
|
89
|
+
columns.append(_Column(
|
|
90
|
+
index=int(_get(item, "Index")),
|
|
91
|
+
name=str(_get(item, "Name")),
|
|
92
|
+
type=_TYPE_ALIASES[type_name],
|
|
93
|
+
trimmed=bool(_get(item, "Trimmed", True)),
|
|
94
|
+
bypass_empty=bool(_get(item, "BypassEmptyValue", True)),
|
|
95
|
+
))
|
|
96
|
+
return columns
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
# --- lecture du classeur ---------------------------------------------------------------
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _read_sheets(path: str) -> dict[str, list[tuple]]:
|
|
103
|
+
if path.lower().endswith(".xls"):
|
|
104
|
+
try:
|
|
105
|
+
import xlrd
|
|
106
|
+
except ImportError as exc:
|
|
107
|
+
raise JsltError("loadxls : les fichiers .xls exigent l'extra urban-json-excel[xls] (xlrd)") from exc
|
|
108
|
+
book = xlrd.open_workbook(path)
|
|
109
|
+
sheets = {}
|
|
110
|
+
for sheet in book.sheets():
|
|
111
|
+
rows = []
|
|
112
|
+
for r in range(sheet.nrows):
|
|
113
|
+
row = []
|
|
114
|
+
for c in range(sheet.ncols):
|
|
115
|
+
cell = sheet.cell(r, c)
|
|
116
|
+
if cell.ctype == xlrd.XL_CELL_DATE:
|
|
117
|
+
row.append(xlrd.xldate.xldate_as_datetime(cell.value, book.datemode))
|
|
118
|
+
elif cell.ctype in (xlrd.XL_CELL_EMPTY, xlrd.XL_CELL_BLANK):
|
|
119
|
+
row.append(None)
|
|
120
|
+
elif cell.ctype == xlrd.XL_CELL_BOOLEAN:
|
|
121
|
+
row.append(bool(cell.value))
|
|
122
|
+
else:
|
|
123
|
+
row.append(cell.value)
|
|
124
|
+
rows.append(tuple(row))
|
|
125
|
+
sheets[sheet.name] = rows
|
|
126
|
+
return sheets
|
|
127
|
+
import openpyxl
|
|
128
|
+
|
|
129
|
+
workbook = openpyxl.load_workbook(path, read_only=True, data_only=True)
|
|
130
|
+
try:
|
|
131
|
+
return {ws.title: [tuple(row) for row in ws.iter_rows(values_only=True)] for ws in workbook.worksheets}
|
|
132
|
+
finally:
|
|
133
|
+
workbook.close()
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def _label(name: str) -> str:
|
|
137
|
+
"""Assainit un nom de colonne (``ExcelReader.GetLabel``, comme ``loadcsv``)."""
|
|
138
|
+
decomposed = unicodedata.normalize("NFKD", name)
|
|
139
|
+
out = []
|
|
140
|
+
for char in decomposed:
|
|
141
|
+
if unicodedata.combining(char):
|
|
142
|
+
continue
|
|
143
|
+
if char.isascii() and char.isalnum():
|
|
144
|
+
out.append(char)
|
|
145
|
+
elif char in (" ", "'", '"', "_"):
|
|
146
|
+
out.append("_")
|
|
147
|
+
label = "".join(out)
|
|
148
|
+
while "__" in label:
|
|
149
|
+
label = label.replace("__", "_")
|
|
150
|
+
return label
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def _is_integral(value: Any) -> bool:
|
|
154
|
+
if isinstance(value, bool):
|
|
155
|
+
return False
|
|
156
|
+
if isinstance(value, int):
|
|
157
|
+
return True
|
|
158
|
+
return isinstance(value, float) and value.is_integer()
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def _auto_columns(header: list[Any], data: list[tuple], header_line: int) -> list[_Column]:
|
|
162
|
+
columns: list[_Column] = []
|
|
163
|
+
width = max([len(header)] + [len(r) for r in data]) if (header or data) else 0
|
|
164
|
+
if header_line > 0:
|
|
165
|
+
names = data[header_line] if header_line < len(data) else ()
|
|
166
|
+
for index in range(width):
|
|
167
|
+
name = names[index] if index < len(names) else None
|
|
168
|
+
if isinstance(name, str):
|
|
169
|
+
text = name.strip(" \t\r\n")
|
|
170
|
+
label = _label(text) if text else f"renamed_{len(columns)}"
|
|
171
|
+
elif name is not None:
|
|
172
|
+
label = f"renamed_{len(columns)}"
|
|
173
|
+
else:
|
|
174
|
+
continue # colonne sans en-tête : ignorée, comme le .NET
|
|
175
|
+
columns.append(_Column(index, label, "auto"))
|
|
176
|
+
return columns
|
|
177
|
+
seen: set[str] = set()
|
|
178
|
+
for index in range(width):
|
|
179
|
+
raw = header[index] if index < len(header) and header[index] not in (None, "") else f"Column{index}"
|
|
180
|
+
name = _label(str(raw)) or f"Column{index}"
|
|
181
|
+
if name in seen:
|
|
182
|
+
name += f"_renamed_{index}"
|
|
183
|
+
seen.add(name)
|
|
184
|
+
values = [r[index] for r in data if index < len(r) and r[index] is not None]
|
|
185
|
+
kind = "integer" if values and all(_is_integral(v) for v in values) else "auto"
|
|
186
|
+
columns.append(_Column(index, name, kind))
|
|
187
|
+
return columns
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def _iso(value: Any) -> Any:
|
|
191
|
+
if isinstance(value, (datetime, date, time)):
|
|
192
|
+
return value.isoformat()
|
|
193
|
+
return value
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def _convert(value: Any, column: _Column) -> Any:
|
|
197
|
+
"""Valeur typée d'une cellule, ou ``_SKIP`` pour l'omettre."""
|
|
198
|
+
if value is None:
|
|
199
|
+
return _SKIP
|
|
200
|
+
# Colonne automatique contenant du texte : traitée comme une colonne texte (le
|
|
201
|
+
# .NET lui attribue le type string, donc nettoyage et valeurs vides omises).
|
|
202
|
+
if column.type == "string" or (column.type == "auto" and isinstance(value, str)):
|
|
203
|
+
text = value if isinstance(value, str) else str(_iso(value))
|
|
204
|
+
if column.trimmed:
|
|
205
|
+
text = text.strip()
|
|
206
|
+
return _SKIP if column.bypass_empty and text == "" else text
|
|
207
|
+
if isinstance(value, str) and value.strip() == "":
|
|
208
|
+
return _SKIP
|
|
209
|
+
try:
|
|
210
|
+
if column.type == "integer":
|
|
211
|
+
return int(float(value)) if not isinstance(value, bool) else int(value)
|
|
212
|
+
if column.type == "number":
|
|
213
|
+
return float(value)
|
|
214
|
+
if column.type == "boolean":
|
|
215
|
+
return value if isinstance(value, bool) else str(value).strip().lower() in ("true", "1", "vrai", "yes")
|
|
216
|
+
except (TypeError, ValueError):
|
|
217
|
+
return _iso(value) # conversion impossible : valeur d'origine, comme le .NET
|
|
218
|
+
if column.type == "datetime" and isinstance(value, str):
|
|
219
|
+
return value
|
|
220
|
+
return _iso(value)
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
_SKIP = object()
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def _read(path: str, config: dict) -> list[dict]:
|
|
227
|
+
if not os.path.isfile(path):
|
|
228
|
+
raise JsltError(f"loadxls : classeur introuvable {path!r}")
|
|
229
|
+
sheets = _read_sheets(path)
|
|
230
|
+
table = _get(config, "Tablename") or ""
|
|
231
|
+
if table:
|
|
232
|
+
if table not in sheets:
|
|
233
|
+
raise JsltError(f"loadxls : feuille {table!r} introuvable (feuilles : {', '.join(sheets)})")
|
|
234
|
+
elif len(sheets) == 1:
|
|
235
|
+
table = next(iter(sheets))
|
|
236
|
+
else:
|
|
237
|
+
raise JsltError("loadxls : Tablename non précisé alors que le classeur a plusieurs feuilles")
|
|
238
|
+
|
|
239
|
+
rows = sheets[table]
|
|
240
|
+
first_row_names = bool(_get(config, "FirstRowHasColumnName", False))
|
|
241
|
+
header = list(rows[0]) if first_row_names and rows else []
|
|
242
|
+
data = rows[1:] if first_row_names else rows
|
|
243
|
+
header_line = int(_get(config, "HeaderLine", 0) or 0)
|
|
244
|
+
add_row_number = bool(_get(config, "AddRowNumber", True))
|
|
245
|
+
bypass_empty_object = bool(_get(config, "ByPassEmptyObject", True))
|
|
246
|
+
columns = _columns_from_config(config) or _auto_columns(header, data, header_line)
|
|
247
|
+
|
|
248
|
+
result = []
|
|
249
|
+
for row_line, row in enumerate(data):
|
|
250
|
+
if header_line and row_line <= header_line:
|
|
251
|
+
continue
|
|
252
|
+
obj: dict[str, Any] = {}
|
|
253
|
+
for column in columns:
|
|
254
|
+
value = row[column.index] if column.index < len(row) else None
|
|
255
|
+
converted = _convert(value, column)
|
|
256
|
+
if converted is not _SKIP:
|
|
257
|
+
obj[column.name] = converted
|
|
258
|
+
if obj or not bypass_empty_object:
|
|
259
|
+
if add_row_number:
|
|
260
|
+
obj["$row"] = row_line
|
|
261
|
+
result.append(obj)
|
|
262
|
+
return result
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def execute_loadxlssheet(ctx: Any, source_path: Any = None, config: Any = None) -> list:
|
|
266
|
+
if not source_path:
|
|
267
|
+
raise JsltError("loadxlssheet : le chemin du classeur est requis")
|
|
268
|
+
if config is None:
|
|
269
|
+
config = {}
|
|
270
|
+
if not isinstance(config, dict):
|
|
271
|
+
raise JsltError("loadxlssheet : la configuration doit être un objet JSON")
|
|
272
|
+
return _read(str(source_path), config)
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def execute_loadxls(ctx: Any, source_path: Any = None, config_path: Any = None) -> list:
|
|
276
|
+
if not source_path:
|
|
277
|
+
raise JsltError("loadxls : le chemin du classeur est requis")
|
|
278
|
+
if not config_path or not os.path.isfile(str(config_path)):
|
|
279
|
+
raise JsltError(f"loadxls : fichier de configuration introuvable {config_path!r}")
|
|
280
|
+
try:
|
|
281
|
+
with open(str(config_path), encoding="utf-8-sig") as handle:
|
|
282
|
+
config = json.load(handle)
|
|
283
|
+
except json.JSONDecodeError as exc:
|
|
284
|
+
raise JsltError(f"loadxls : fichier de configuration JSON invalide ({exc})") from exc
|
|
285
|
+
if not isinstance(config, dict):
|
|
286
|
+
raise JsltError("loadxls : la configuration doit être un objet JSON")
|
|
287
|
+
return _read(str(source_path), config)
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
def register(registry: Any) -> None:
|
|
291
|
+
"""Enregistre ``loadxls`` et ``loadxlssheet``."""
|
|
292
|
+
registry.register(
|
|
293
|
+
"loadxls", execute_loadxls,
|
|
294
|
+
description="Lit une feuille Excel en tableau d'objets, selon un fichier de configuration JSON",
|
|
295
|
+
)
|
|
296
|
+
registry.register(
|
|
297
|
+
"loadxlssheet", execute_loadxlssheet,
|
|
298
|
+
description="Lit une feuille Excel en tableau d'objets, selon un objet de configuration",
|
|
299
|
+
)
|
|
File without changes
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: urban-json-excel
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Plugin urban-json : lecture de classeurs Excel (loadxls, loadxlssheet).
|
|
5
|
+
Author-email: Gael Beard <gaelgael5@gmail.com>
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://github.com/gaelgael5/Jslt
|
|
8
|
+
Project-URL: Repository, https://github.com/gaelgael5/Jslt
|
|
9
|
+
Keywords: json,transform,template,jslt,excel,plugin
|
|
10
|
+
Classifier: Development Status :: 3 - Alpha
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
19
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
20
|
+
Classifier: Topic :: Text Processing :: Markup
|
|
21
|
+
Classifier: Typing :: Typed
|
|
22
|
+
Requires-Python: >=3.9
|
|
23
|
+
Description-Content-Type: text/markdown
|
|
24
|
+
License-File: LICENSE
|
|
25
|
+
Requires-Dist: urban-json
|
|
26
|
+
Requires-Dist: openpyxl>=3.1
|
|
27
|
+
Provides-Extra: xls
|
|
28
|
+
Requires-Dist: xlrd>=2.0; extra == "xls"
|
|
29
|
+
Dynamic: license-file
|
|
30
|
+
|
|
31
|
+
# urban-json-excel
|
|
32
|
+
|
|
33
|
+
Plugin [urban-json](https://github.com/gaelgael5/Jslt) : **classeurs Excel** dans les
|
|
34
|
+
templates (port de `ServicesXls` / `ExcelReader`, .NET).
|
|
35
|
+
|
|
36
|
+
```bash
|
|
37
|
+
pip install urban-json-excel # .xlsx (openpyxl)
|
|
38
|
+
pip install "urban-json-excel[xls]" # + anciens .xls (xlrd)
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
- `loadxls(classeur, "config.json")` — configuration lue dans un fichier JSON ;
|
|
42
|
+
- `loadxlssheet(classeur, { … })` — configuration passée en objet.
|
|
43
|
+
|
|
44
|
+
```json
|
|
45
|
+
{ "FirstRowHasColumnName": true, "HeaderLine": 0, "Tablename": "Feuil1",
|
|
46
|
+
"AddRowNumber": true, "ByPassEmptyObject": true,
|
|
47
|
+
"Columns": [ { "Index": 0, "Name": "id", "Type": "integer", "Trimmed": true, "BypassEmptyValue": true } ] }
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
Chaque ligne devient un objet (`"$row"` = rang de la ligne de données si
|
|
51
|
+
`AddRowNumber`). Sans `Columns`, toutes les colonnes sont lues, noms assainis
|
|
52
|
+
(`"Nom complet"` → `Nom_complet`) et colonnes entièrement entières typées `integer`.
|
|
53
|
+
Si `Tablename` est vide, la feuille unique du classeur est prise.
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
src/urban_json_excel/__init__.py
|
|
5
|
+
src/urban_json_excel/py.typed
|
|
6
|
+
src/urban_json_excel.egg-info/PKG-INFO
|
|
7
|
+
src/urban_json_excel.egg-info/SOURCES.txt
|
|
8
|
+
src/urban_json_excel.egg-info/dependency_links.txt
|
|
9
|
+
src/urban_json_excel.egg-info/entry_points.txt
|
|
10
|
+
src/urban_json_excel.egg-info/requires.txt
|
|
11
|
+
src/urban_json_excel.egg-info/top_level.txt
|
|
12
|
+
tests/test_excel.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
urban_json_excel
|
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
"""loadxls / loadxlssheet — port de ServicesXls + ExcelReader (.NET)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from datetime import datetime
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
import openpyxl
|
|
10
|
+
import pytest
|
|
11
|
+
from urban_json import FunctionRegistry, JsltError, JsltTemplate
|
|
12
|
+
|
|
13
|
+
from urban_json_excel import register
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@pytest.fixture(scope="module")
|
|
17
|
+
def registry() -> FunctionRegistry:
|
|
18
|
+
reg = FunctionRegistry()
|
|
19
|
+
register(reg)
|
|
20
|
+
return reg
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _book(tmp_path: Path, sheets: dict[str, list[list]]) -> str:
|
|
24
|
+
workbook = openpyxl.Workbook()
|
|
25
|
+
workbook.remove(workbook.active)
|
|
26
|
+
for name, rows in sheets.items():
|
|
27
|
+
sheet = workbook.create_sheet(name)
|
|
28
|
+
for row in rows:
|
|
29
|
+
sheet.append(row)
|
|
30
|
+
path = tmp_path / "book.xlsx"
|
|
31
|
+
workbook.save(path)
|
|
32
|
+
return str(path)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def sheet(registry, path: str, config: dict):
|
|
36
|
+
template = JsltTemplate.parse('{ "r": loadxlssheet($.p, $.c) }')
|
|
37
|
+
return template.transform({"p": path, "c": config}, functions=registry)["r"]
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
# Excel ne stocke pas de fuseau : date « naïve » volontaire.
|
|
41
|
+
PEOPLE = [["Nom complet", "Âge", "Inscrit le"], [" Ana ", 30, datetime(2026, 1, 2)], ["Bob", 41, None]] # noqa: DTZ001
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def test_en_tete_premiere_ligne(registry, tmp_path) -> None:
|
|
45
|
+
path = _book(tmp_path, {"Gens": PEOPLE})
|
|
46
|
+
out = sheet(registry, path, {"FirstRowHasColumnName": True})
|
|
47
|
+
assert out == [
|
|
48
|
+
{"Nom_complet": "Ana", "Age": 30, "Inscrit_le": "2026-01-02T00:00:00", "$row": 0},
|
|
49
|
+
{"Nom_complet": "Bob", "Age": 41, "$row": 1},
|
|
50
|
+
]
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def test_sans_en_tete_noms_column_n(registry, tmp_path) -> None:
|
|
54
|
+
path = _book(tmp_path, {"S": [["a", 1], ["b", 2]]})
|
|
55
|
+
out = sheet(registry, path, {"AddRowNumber": False})
|
|
56
|
+
assert out == [{"Column0": "a", "Column1": 1}, {"Column0": "b", "Column1": 2}]
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def test_colonne_decimale_reste_decimale(registry, tmp_path) -> None:
|
|
60
|
+
path = _book(tmp_path, {"S": [["v"], [1.5], [2]]})
|
|
61
|
+
assert [r["v"] for r in sheet(registry, path, {"FirstRowHasColumnName": True})] == [1.5, 2.0]
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def test_header_line(registry, tmp_path) -> None:
|
|
65
|
+
rows = [["titre du rapport"], [None], ["Code", "Libellé"], ["A1", "Un"], ["B2", "Deux"]]
|
|
66
|
+
path = _book(tmp_path, {"S": rows})
|
|
67
|
+
out = sheet(registry, path, {"HeaderLine": 2, "AddRowNumber": False})
|
|
68
|
+
assert out == [{"Code": "A1", "Libelle": "Un"}, {"Code": "B2", "Libelle": "Deux"}]
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def test_colonnes_explicites_types_et_filtre(registry, tmp_path) -> None:
|
|
72
|
+
path = _book(tmp_path, {"S": [["id", "montant", "note"], ["7", "12.5", " x "], ["8", "3", ""]]})
|
|
73
|
+
config = {
|
|
74
|
+
"FirstRowHasColumnName": True, "AddRowNumber": False,
|
|
75
|
+
"Columns": [
|
|
76
|
+
{"Index": 0, "Name": "id", "Type": "integer"},
|
|
77
|
+
{"Index": 1, "Name": "montant", "Type": "decimal"},
|
|
78
|
+
{"Index": 2, "Name": "note", "Trimmed": False},
|
|
79
|
+
],
|
|
80
|
+
}
|
|
81
|
+
assert sheet(registry, path, config) == [
|
|
82
|
+
{"id": 7, "montant": 12.5, "note": " x "},
|
|
83
|
+
{"id": 8, "montant": 3.0}, # valeur vide omise (BypassEmptyValue par défaut)
|
|
84
|
+
]
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def test_lignes_vides_omises_ou_gardees(registry, tmp_path) -> None:
|
|
88
|
+
path = _book(tmp_path, {"S": [["a"], ["x"], [None], ["y"]]})
|
|
89
|
+
kept = sheet(registry, path, {"FirstRowHasColumnName": True, "ByPassEmptyObject": False})
|
|
90
|
+
assert kept == [{"a": "x", "$row": 0}, {"$row": 1}, {"a": "y", "$row": 2}]
|
|
91
|
+
skipped = sheet(registry, path, {"FirstRowHasColumnName": True})
|
|
92
|
+
assert [r["$row"] for r in skipped] == [0, 2]
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def test_noms_de_colonnes_en_double(registry, tmp_path) -> None:
|
|
96
|
+
path = _book(tmp_path, {"S": [["a", "a"], [1, 2]]})
|
|
97
|
+
assert sheet(registry, path, {"FirstRowHasColumnName": True, "AddRowNumber": False}) == [{"a": 1, "a_renamed_1": 2}]
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def test_choix_de_la_feuille(registry, tmp_path) -> None:
|
|
101
|
+
path = _book(tmp_path, {"Un": [["v"], [1]], "Deux": [["v"], [2]]})
|
|
102
|
+
assert sheet(registry, path, {"Tablename": "Deux", "FirstRowHasColumnName": True})[0]["v"] == 2
|
|
103
|
+
with pytest.raises(JsltError, match="plusieurs feuilles"):
|
|
104
|
+
sheet(registry, path, {"FirstRowHasColumnName": True})
|
|
105
|
+
with pytest.raises(JsltError, match="feuille"):
|
|
106
|
+
sheet(registry, path, {"Tablename": "Trois"})
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def test_feuille_unique_sans_nom(registry, tmp_path) -> None:
|
|
110
|
+
# Le .NET échouait toujours ici (bug) : la feuille unique est prise.
|
|
111
|
+
path = _book(tmp_path, {"Seule": [["v"], [1]]})
|
|
112
|
+
assert sheet(registry, path, {"FirstRowHasColumnName": True})[0]["v"] == 1
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def test_cles_de_configuration_insensibles_a_la_casse(registry, tmp_path) -> None:
|
|
116
|
+
path = _book(tmp_path, {"S": [["v"], [1]]})
|
|
117
|
+
assert sheet(registry, path, {"firstRowHasColumnName": True, "addrownumber": False}) == [{"v": 1}]
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def test_loadxls_avec_fichier_de_configuration(registry, tmp_path) -> None:
|
|
121
|
+
path = _book(tmp_path, {"S": [["v"], [1]]})
|
|
122
|
+
config = tmp_path / "conf.json"
|
|
123
|
+
config.write_text(json.dumps({"FirstRowHasColumnName": True, "AddRowNumber": False}), encoding="utf-8")
|
|
124
|
+
template = JsltTemplate.parse('{ "r": loadxls($.p, $.c) }')
|
|
125
|
+
assert template.transform({"p": path, "c": str(config)}, functions=registry)["r"] == [{"v": 1}]
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
@pytest.mark.parametrize(
|
|
129
|
+
("expression", "message"),
|
|
130
|
+
[
|
|
131
|
+
('loadxls($.p, "/absent/conf.json")', "configuration"),
|
|
132
|
+
('loadxlssheet("/absent/book.xlsx", {})', "introuvable"),
|
|
133
|
+
("loadxlssheet($.p, 3)", "configuration"),
|
|
134
|
+
],
|
|
135
|
+
)
|
|
136
|
+
def test_erreurs(registry, tmp_path, expression, message) -> None:
|
|
137
|
+
path = _book(tmp_path, {"S": [["v"], [1]]})
|
|
138
|
+
template = JsltTemplate.parse(f'{{ "r": {expression} }}')
|
|
139
|
+
with pytest.raises(JsltError, match=message):
|
|
140
|
+
template.transform({"p": path}, functions=registry)
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def test_catalogue_et_decouverte(registry) -> None:
|
|
144
|
+
from urban_json import default_registry, load_plugins
|
|
145
|
+
|
|
146
|
+
assert {e["name"] for e in registry.catalog()} == {"loadxls", "loadxlssheet"}
|
|
147
|
+
assert all(len(e["description"]) >= 15 for e in registry.catalog())
|
|
148
|
+
load_plugins()
|
|
149
|
+
assert "loadxlssheet" in default_registry
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
# --- .xls (Excel 97-2003, BIFF8) ------------------------------------------------------
|
|
153
|
+
|
|
154
|
+
# tests/data/sample.xls : vrai classeur BIFF8 produit avec xlwt, même contenu que XLS_ROWS.
|
|
155
|
+
XLS_SAMPLE = str(Path(__file__).parent / "data" / "sample.xls")
|
|
156
|
+
XLS_ROWS = [
|
|
157
|
+
["Nom", "Age", "Taille", "Actif", "Naissance", "Note"],
|
|
158
|
+
[" Alice ", 30, 1.68, True, datetime(1994, 5, 17), "ok"], # noqa: DTZ001
|
|
159
|
+
[None, None, None, None, None, None],
|
|
160
|
+
["Bob", 42, 1.8, False, datetime(1982, 1, 2), None], # noqa: DTZ001
|
|
161
|
+
]
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
@pytest.mark.parametrize(
|
|
165
|
+
"config",
|
|
166
|
+
[
|
|
167
|
+
pytest.param({"FirstRowHasColumnName": True}, id="colonnes-auto"),
|
|
168
|
+
pytest.param({"FirstRowHasColumnName": True, "ByPassEmptyObject": False}, id="ligne-vide-gardee"),
|
|
169
|
+
pytest.param(
|
|
170
|
+
{
|
|
171
|
+
"FirstRowHasColumnName": True,
|
|
172
|
+
"Columns": [
|
|
173
|
+
{"Index": 0, "Name": "nom", "Type": "string"},
|
|
174
|
+
{"Index": 1, "Name": "age", "Type": "integer"},
|
|
175
|
+
{"Index": 2, "Name": "taille", "Type": "decimal"},
|
|
176
|
+
{"Index": 3, "Name": "actif", "Type": "boolean"},
|
|
177
|
+
{"Index": 4, "Name": "naissance", "Type": "datetime"},
|
|
178
|
+
],
|
|
179
|
+
},
|
|
180
|
+
id="colonnes-typees",
|
|
181
|
+
),
|
|
182
|
+
],
|
|
183
|
+
)
|
|
184
|
+
def test_xls_identique_au_xlsx(registry, tmp_path, config) -> None:
|
|
185
|
+
pytest.importorskip("xlrd")
|
|
186
|
+
expected = sheet(registry, _book(tmp_path, {"Feuil1": XLS_ROWS}), config)
|
|
187
|
+
assert sheet(registry, XLS_SAMPLE, config) == expected
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def test_xls_valeurs(registry) -> None:
|
|
191
|
+
pytest.importorskip("xlrd")
|
|
192
|
+
out = sheet(registry, XLS_SAMPLE, {"FirstRowHasColumnName": True})
|
|
193
|
+
assert out == [
|
|
194
|
+
{"Nom": "Alice", "Age": 30, "Taille": 1.68, "Actif": True, "Naissance": "1994-05-17T00:00:00",
|
|
195
|
+
"Note": "ok", "$row": 0},
|
|
196
|
+
{"Nom": "Bob", "Age": 42, "Taille": 1.8, "Actif": False, "Naissance": "1982-01-02T00:00:00", "$row": 2},
|
|
197
|
+
]
|