mirror of
https://github.com/Hestia-Homes/Model.git
synced 2026-06-08 11:17:27 +00:00
write to excel file 🟩
This commit is contained in:
parent
0b301c4473
commit
e10e29b581
1 changed files with 48 additions and 1 deletions
|
|
@ -1,5 +1,52 @@
|
|||
import os
|
||||
from typing import Any
|
||||
|
||||
from openpyxl import Workbook, load_workbook
|
||||
from openpyxl.worksheet.worksheet import Worksheet
|
||||
|
||||
|
||||
def write_row(file_path: str, row_data: dict[str, Any]) -> None:
|
||||
raise NotImplementedError
|
||||
new_keys = list(row_data.keys())
|
||||
|
||||
if not os.path.exists(file_path):
|
||||
wb = Workbook()
|
||||
ws: Worksheet = wb.active # type: ignore[assignment]
|
||||
ws.append(new_keys)
|
||||
ws.append(list(row_data.values()))
|
||||
wb.save(file_path)
|
||||
return
|
||||
|
||||
wb = load_workbook(file_path)
|
||||
ws = wb.active # type: ignore[assignment]
|
||||
|
||||
# Build a mutable header list and insert new columns using insert_cols so
|
||||
# that existing row data shifts along with the headers.
|
||||
headers: list[str] = [cell.value for cell in ws[1]] # type: ignore[misc]
|
||||
|
||||
for key in new_keys:
|
||||
if key in headers:
|
||||
continue
|
||||
|
||||
# Find the first key that comes after this one in new_keys that already
|
||||
# exists in headers — insert before it to keep columns logically grouped.
|
||||
insert_before: str | None = None
|
||||
found = False
|
||||
for k in new_keys:
|
||||
if k == key:
|
||||
found = True
|
||||
continue
|
||||
if found and k in headers:
|
||||
insert_before = k
|
||||
break
|
||||
|
||||
if insert_before is not None:
|
||||
col_idx = headers.index(insert_before) + 1 # 1-based
|
||||
ws.insert_cols(col_idx)
|
||||
ws.cell(row=1, column=col_idx, value=key)
|
||||
headers.insert(col_idx - 1, key)
|
||||
else:
|
||||
headers.append(key)
|
||||
ws.cell(row=1, column=len(headers), value=key)
|
||||
|
||||
ws.append([row_data.get(col) for col in headers])
|
||||
wb.save(file_path)
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue