"""把表格读成小区多期记录,并按选择的格式写出。""" from __future__ import annotations import csv import io from datetime import datetime, timezone from openpyxl import Workbook, load_workbook import xlwt CELL_HEADERS = ("小区", "cell_key", "cell") TIME_HEADERS = ("时间", "observed_at", "time") def decode_text(content: bytes) -> str: for encoding in ("utf-8-sig", "gbk"): try: return content.decode(encoding) except UnicodeDecodeError: continue return content.decode("utf-8", errors="replace") def _parse_time(value: str) -> datetime: text = value.strip() if not text: raise ValueError("缺少时间") normalized = text.replace("/", "-").replace("T", " ") for fmt in ("%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M", "%Y-%m-%d"): try: parsed = datetime.strptime(normalized, fmt) return parsed.replace(tzinfo=timezone.utc) except ValueError: continue raise ValueError("时间格式无法识别") def rows_from_table(headers: list[str], records: list[list[str]]) -> list[dict]: cell_index = next((index for index, name in enumerate(headers) if name.strip() in CELL_HEADERS), None) time_index = next((index for index, name in enumerate(headers) if name.strip() in TIME_HEADERS), None) if cell_index is None or time_index is None: raise ValueError("表格需要包含小区和时间") parsed: list[dict] = [] for record in records: if cell_index >= len(record) or not str(record[cell_index]).strip(): continue metrics = {} for index, name in enumerate(headers): if index in {cell_index, time_index} or not name.strip(): continue metrics[name.strip()] = "" if index >= len(record) else str(record[index]).strip() parsed.append( { "cell_key": str(record[cell_index]).strip(), "observed_at": _parse_time(str(record[time_index]) if time_index < len(record) else ""), "metrics": metrics, } ) return parsed def parse_csv(content: bytes) -> list[dict]: reader = csv.reader(io.StringIO(decode_text(content))) rows = list(reader) if not rows: return [] return rows_from_table(rows[0], rows[1:]) def parse_xlsx(content: bytes) -> list[dict]: book = load_workbook(io.BytesIO(content), read_only=True, data_only=True) sheet = book.active rows = [["" if cell is None else str(cell) for cell in row] for row in sheet.iter_rows(values_only=True)] book.close() if not rows: return [] return rows_from_table(rows[0], rows[1:]) def parse_upload(name: str, content: bytes) -> list[dict]: lowered = name.lower() if lowered.endswith(".xlsx"): return parse_xlsx(content) return parse_csv(content) def _flat_rows(rows: list[dict]) -> tuple[list[str], list[list[str]]]: metric_names: list[str] = [] for row in rows: for key in row["metrics"]: if key not in metric_names: metric_names.append(key) headers = ["小区", "时间", *metric_names] body = [] for row in rows: moment = row["observed_at"] if isinstance(moment, datetime): text = moment.astimezone(timezone.utc).strftime("%Y-%m-%d %H:%M:%S") else: text = str(moment) body.append([row["cell_key"], text, *[str(row["metrics"].get(name, "")) for name in metric_names]]) return headers, body def write_csv(rows: list[dict]) -> bytes: headers, body = _flat_rows(rows) buffer = io.StringIO() writer = csv.writer(buffer) writer.writerow(headers) writer.writerows(body) return buffer.getvalue().encode("utf-8-sig") def write_xlsx(rows: list[dict]) -> bytes: headers, body = _flat_rows(rows) book = Workbook() sheet = book.active sheet.append(headers) for line in body: sheet.append(line) buffer = io.BytesIO() book.save(buffer) return buffer.getvalue() def write_xls(rows: list[dict]) -> bytes: headers, body = _flat_rows(rows) book = xlwt.Workbook() sheet = book.add_sheet("结果") for column, name in enumerate(headers): sheet.write(0, column, name) for row_index, line in enumerate(body, start=1): for column, value in enumerate(line): sheet.write(row_index, column, value) buffer = io.BytesIO() book.save(buffer) return buffer.getvalue() def write_table(file_format: str, rows: list[dict]) -> tuple[str, bytes]: if file_format == "xlsx": return "result.xlsx", write_xlsx(rows) if file_format == "xls": return "result.xls", write_xls(rows) if file_format == "csv": return "result.csv", write_csv(rows) raise ValueError("结果文件只能是 xlsx、xls 或 csv")