Files
kadastr-17/read_one_file_xlsx.py
2026-03-10 20:21:31 +05:00

50 lines
1.6 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
from pathlib import Path
from typing import Any, Dict, List
def read_xlsx(file_path: str) -> Dict[str, Any]:
"""
Прочитать .xlsx файл и вернуть простой объект со всеми данными.
Возвращаемая структура:
{
'name': <file name>,
'path': <abs path>,
'sheets': [
{'name': <sheet name>, 'rows': [[cell_value, ...], ...]},
...
]
}
Читает документ сверху-вниз, сохраняя значения ячеек в их питоновских типах.
"""
p = Path(file_path)
if not p.exists():
raise FileNotFoundError(file_path)
# try openpyxl first
try:
from openpyxl import load_workbook
except Exception as e:
raise RuntimeError("openpyxl is required to read .xlsx files") from e
wb = load_workbook(filename=str(p), data_only=True)
out = {"name": p.name, "path": str(p.resolve()), "sheets": []}
for sheet in wb.worksheets:
rows: List[List[Any]] = []
for row in sheet.iter_rows(values_only=True):
rows.append(list(row))
out["sheets"].append({"name": sheet.title, "rows": rows})
return out
if __name__ == "__main__":
import sys, json
target = sys.argv[1] if len(sys.argv) > 1 else "data/Исх.данные/Таблица1 КИ-Неустроева.xlsx"
try:
data = read_xlsx(target)
print(json.dumps(data, ensure_ascii=False, indent=2, default=str))
except Exception as exc:
print('Error:', exc)