#!/usr/bin/env python3 """ Generate batch INSERT SQL for departments table from Excel (.xlsx). Mapping (first sheet): - 部门编号 -> departments.code - 部门名称 -> departments.name - 公司名称 -> departments.company """ from __future__ import annotations import argparse import re import sys import xml.etree.ElementTree as ET import zipfile from pathlib import Path from typing import Dict, List, Tuple NS_MAIN = "http://schemas.openxmlformats.org/spreadsheetml/2006/main" NS_REL = "http://schemas.openxmlformats.org/officeDocument/2006/relationships" NS_PKG = "http://schemas.openxmlformats.org/package/2006/relationships" NS = {"a": NS_MAIN} def _cell_col_index(cell_ref: str) -> int: match = re.match(r"([A-Z]+)", cell_ref) if not match: return 0 idx = 0 for ch in match.group(1): idx = idx * 26 + (ord(ch) - ord("A") + 1) return idx - 1 def _get_cell_value(cell: ET.Element, shared_strings: List[str]) -> str: cell_type = cell.attrib.get("t") inline_node = cell.find("a:is", NS) if inline_node is not None: return "".join(t.text or "" for t in inline_node.findall(".//a:t", NS)).strip() value_node = cell.find("a:v", NS) if value_node is None or value_node.text is None: return "" raw = value_node.text.strip() if cell_type == "s" and raw.isdigit(): idx = int(raw) if 0 <= idx < len(shared_strings): return shared_strings[idx].strip() return raw def _read_shared_strings(zf: zipfile.ZipFile) -> List[str]: if "xl/sharedStrings.xml" not in zf.namelist(): return [] root = ET.fromstring(zf.read("xl/sharedStrings.xml")) return [ "".join(t.text or "" for t in si.findall(".//a:t", NS)).strip() for si in root.findall("a:si", NS) ] def _first_sheet_path(zf: zipfile.ZipFile) -> str: workbook = ET.fromstring(zf.read("xl/workbook.xml")) sheets = workbook.find("a:sheets", NS) if sheets is None: raise ValueError("No sheets found in workbook.") first_sheet = sheets.find("a:sheet", NS) if first_sheet is None: raise ValueError("No sheet found in workbook.") rid = first_sheet.attrib.get(f"{{{NS_REL}}}id") if not rid: raise ValueError("Cannot resolve first sheet relationship id.") rels = ET.fromstring(zf.read("xl/_rels/workbook.xml.rels")) rel_map = { rel.attrib["Id"]: rel.attrib["Target"] for rel in rels.findall(f"{{{NS_PKG}}}Relationship") } target = rel_map.get(rid) if not target: raise ValueError("Cannot resolve first sheet target.") if target.startswith("/"): target = target[1:] if not target.startswith("xl/"): target = f"xl/{target}" return target def read_xlsx_rows(xlsx_path: Path) -> List[List[str]]: with zipfile.ZipFile(xlsx_path, "r") as zf: shared = _read_shared_strings(zf) sheet_path = _first_sheet_path(zf) root = ET.fromstring(zf.read(sheet_path)) rows: List[List[str]] = [] for row in root.findall(".//a:sheetData/a:row", NS): cells = row.findall("a:c", NS) if not cells: rows.append([]) continue row_map: Dict[int, str] = {} max_idx = 0 for cell in cells: ref = cell.attrib.get("r", "A1") idx = _cell_col_index(ref) max_idx = max(max_idx, idx) row_map[idx] = _get_cell_value(cell, shared) rows.append([row_map.get(i, "").strip() for i in range(max_idx + 1)]) return rows def sql_quote(value: str) -> str: return "'" + value.replace("'", "''") + "'" def build_sql(rows: List[List[str]]) -> Tuple[str, int]: if not rows: raise ValueError("Excel is empty.") header = rows[0] idx_map = {name: idx for idx, name in enumerate(header)} required = ["部门编号", "部门名称", "公司名称"] missing = [c for c in required if c not in idx_map] if missing: raise ValueError(f"Missing required columns: {', '.join(missing)}") by_code: Dict[str, Tuple[str, str]] = {} for row in rows[1:]: code = row[idx_map["部门编号"]].strip() if idx_map["部门编号"] < len(row) else "" name = row[idx_map["部门名称"]].strip() if idx_map["部门名称"] < len(row) else "" company = row[idx_map["公司名称"]].strip() if idx_map["公司名称"] < len(row) else "" if not code or not name: continue if code not in by_code: by_code[code] = (name, company) if not by_code: raise ValueError("No valid department data found.") values = [] for code, (name, company) in sorted(by_code.items(), key=lambda x: x[0]): values.append( f"({sql_quote(code)}, {sql_quote(name)}, {sql_quote(company)})" ) sql = ( "BEGIN;\n\n" "INSERT INTO departments (code, name, company)\nVALUES\n " + ",\n ".join(values) + "\nON CONFLICT (code) DO UPDATE\n" "SET name = EXCLUDED.name,\n" " company = EXCLUDED.company;\n\n" "COMMIT;\n" ) return sql, len(by_code) def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description="Generate departments import SQL from xlsx.") parser.add_argument("--xlsx", required=True, help="Path to source .xlsx file.") parser.add_argument( "--output", default="backend/scripts/generated_department_inserts.sql", help="Output SQL file path.", ) return parser.parse_args() def main() -> int: args = parse_args() xlsx_path = Path(args.xlsx) output_path = Path(args.output) if not xlsx_path.exists(): print(f"ERROR: File not found: {xlsx_path}") return 1 rows = read_xlsx_rows(xlsx_path) sql, dept_count = build_sql(rows) output_path.parent.mkdir(parents=True, exist_ok=True) output_path.write_text(sql, encoding="utf-8") print(f"Generated SQL file: {output_path}") print(f"Departments generated: {dept_count}") return 0 if __name__ == "__main__": sys.exit(main())