"""从区域表里读取栅格 ID。""" from __future__ import annotations import csv import io from pathlib import Path _HEADER_KEYS = { "栅格id", "20米栅格id", "grid20_id", "grid_id", "栅格", "栅格编号", } def normalize_id(value) -> str: if value is None: return "" text = str(value).strip().strip("\ufeff") if text.endswith(".0") and text[:-2].isdigit(): text = text[:-2] if not text or not text.isdigit(): return "" return text def _header_index(header: list[str]) -> int | None: for index, name in enumerate(header): key = name.strip().lower().replace(" ", "").replace("_", "") raw = name.strip().lower().replace(" ", "") if raw in _HEADER_KEYS or key in {"栅格id", "20米栅格id", "grid20id", "gridid"}: return index if "栅格" in name and "id" in raw: return index return None def parse_table(rows: list[list]) -> list[str]: if not rows: return [] header = ["" if cell is None else str(cell).strip() for cell in rows[0]] column = _header_index(header) start = 0 if column is None: column = 0 if not normalize_id(header[0] if header else ""): start = 1 else: start = 1 found: list[str] = [] seen: set[str] = set() for row in rows[start:]: if column >= len(row): continue grid_id = normalize_id(row[column]) if not grid_id or grid_id in seen: continue seen.add(grid_id) found.append(grid_id) return found def _decode_csv(raw: bytes) -> str: for encoding in ("utf-8-sig", "utf-8", "gbk"): try: return raw.decode(encoding) except UnicodeDecodeError: continue return raw.decode("utf-8", "replace") def parse_upload(path: Path) -> list[str]: suffix = path.suffix.lower() if suffix == ".xlsx": from openpyxl import load_workbook book = load_workbook(path, read_only=True, data_only=True) try: sheet = book.active rows = [list(row) for row in sheet.iter_rows(values_only=True)] finally: book.close() return parse_table(rows) if suffix not in {".csv", ".txt", ""}: raise ValueError("区域表只支持 CSV、TXT 或 XLSX") text = _decode_csv(path.read_bytes()) sample = text[:4096] try: dialect = csv.Sniffer().sniff(sample, delimiters=",\t;|") except csv.Error: dialect = csv.excel reader = csv.reader(io.StringIO(text), dialect) return parse_table([list(row) for row in reader if any(str(cell).strip() for cell in row)])