test
This commit is contained in:
49
read_one_file_xlsx.py
Normal file
49
read_one_file_xlsx.py
Normal file
@@ -0,0 +1,49 @@
|
||||
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)
|
||||
Reference in New Issue
Block a user