256 lines
7.5 KiB
Python
256 lines
7.5 KiB
Python
#!/usr/bin/env python3
|
|
"""
|
|
Generate batch user INSERT SQL from an Excel (.xlsx) file.
|
|
|
|
Mapping (from first sheet):
|
|
- 工号 -> username, employee_id
|
|
- 姓名 -> real_name
|
|
- 部门名称 -> department
|
|
|
|
Password hashing follows backend logic:
|
|
- werkzeug.security.generate_password_hash
|
|
"""
|
|
|
|
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, Iterable, List
|
|
|
|
from werkzeug.security import generate_password_hash
|
|
|
|
|
|
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
|
|
letters = match.group(1)
|
|
idx = 0
|
|
for ch in letters:
|
|
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 = cell.find("a:is", NS)
|
|
if inline is not None:
|
|
return "".join(node.text or "" for node in inline.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"))
|
|
values: List[str] = []
|
|
for si in root.findall("a:si", NS):
|
|
text = "".join(node.text or "" for node in si.findall(".//a:t", NS)).strip()
|
|
values.append(text)
|
|
return values
|
|
|
|
|
|
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("Workbook does not contain any sheet.")
|
|
|
|
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 path.")
|
|
|
|
if target.startswith("/"):
|
|
target = target[1:]
|
|
if not target.startswith("xl/"):
|
|
target = f"xl/{target}"
|
|
return target
|
|
|
|
|
|
def read_xlsx_first_sheet_rows(xlsx_path: Path) -> List[List[str]]:
|
|
with zipfile.ZipFile(xlsx_path, "r") as zf:
|
|
shared_strings = _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_col = 0
|
|
for cell in cells:
|
|
ref = cell.attrib.get("r", "A1")
|
|
col_idx = _cell_col_index(ref)
|
|
max_col = max(max_col, col_idx)
|
|
row_map[col_idx] = _get_cell_value(cell, shared_strings)
|
|
|
|
normalized = [row_map.get(i, "").strip() for i in range(max_col + 1)]
|
|
rows.append(normalized)
|
|
|
|
return rows
|
|
|
|
|
|
def sql_quote(value: str) -> str:
|
|
return "'" + value.replace("'", "''") + "'"
|
|
|
|
|
|
def build_insert_sql(
|
|
rows: Iterable[List[str]],
|
|
default_password: str,
|
|
email_domain: str,
|
|
role: str,
|
|
status: str,
|
|
language: str,
|
|
) -> str:
|
|
rows = list(rows)
|
|
if not rows:
|
|
raise ValueError("Excel has no rows.")
|
|
|
|
header = rows[0]
|
|
header_idx = {name: idx for idx, name in enumerate(header)}
|
|
required_columns = ["工号", "姓名", "部门名称"]
|
|
missing = [col for col in required_columns if col not in header_idx]
|
|
if missing:
|
|
raise ValueError(f"Missing required columns: {', '.join(missing)}")
|
|
|
|
statements: List[str] = []
|
|
seen_usernames = set()
|
|
|
|
for row in rows[1:]:
|
|
employee_id = row[header_idx["工号"]].strip() if header_idx["工号"] < len(row) else ""
|
|
real_name = row[header_idx["姓名"]].strip() if header_idx["姓名"] < len(row) else ""
|
|
department = row[header_idx["部门名称"]].strip() if header_idx["部门名称"] < len(row) else ""
|
|
|
|
if not employee_id or not real_name:
|
|
continue
|
|
|
|
username = employee_id
|
|
if username in seen_usernames:
|
|
continue
|
|
seen_usernames.add(username)
|
|
|
|
email = f"{employee_id}@{email_domain}"
|
|
password_hash = generate_password_hash(default_password)
|
|
|
|
stmt = (
|
|
"INSERT INTO users "
|
|
"(username, email, real_name, employee_id, department, password_hash, role, status, language)\n"
|
|
f"VALUES ({sql_quote(username)}, {sql_quote(email)}, {sql_quote(real_name)}, "
|
|
f"{sql_quote(employee_id)}, {sql_quote(department)}, {sql_quote(password_hash)}, "
|
|
f"{sql_quote(role)}, {sql_quote(status)}, {sql_quote(language)});"
|
|
)
|
|
statements.append(stmt)
|
|
|
|
if not statements:
|
|
raise ValueError("No valid user rows parsed from Excel.")
|
|
|
|
return "BEGIN;\n\n" + "\n\n".join(statements) + "\n\nCOMMIT;\n"
|
|
|
|
|
|
def parse_args() -> argparse.Namespace:
|
|
parser = argparse.ArgumentParser(
|
|
description="Generate batch INSERT SQL for users table from Excel."
|
|
)
|
|
parser.add_argument(
|
|
"--xlsx",
|
|
required=True,
|
|
help="Path to source Excel file (.xlsx).",
|
|
)
|
|
parser.add_argument(
|
|
"--output",
|
|
default="backend/scripts/generated_user_inserts.sql",
|
|
help="Output SQL file path.",
|
|
)
|
|
parser.add_argument(
|
|
"--default-password",
|
|
default="123456",
|
|
help="Default plain password before hashing.",
|
|
)
|
|
parser.add_argument(
|
|
"--email-domain",
|
|
default="example.com",
|
|
help="Email domain used to generate unique email from employee id.",
|
|
)
|
|
parser.add_argument(
|
|
"--role",
|
|
default="user",
|
|
help="Default user role.",
|
|
)
|
|
parser.add_argument(
|
|
"--status",
|
|
default="active",
|
|
help="Default account status.",
|
|
)
|
|
parser.add_argument(
|
|
"--language",
|
|
default="zh-CN",
|
|
help="Default language.",
|
|
)
|
|
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: Excel file not found: {xlsx_path}")
|
|
return 1
|
|
|
|
rows = read_xlsx_first_sheet_rows(xlsx_path)
|
|
sql = build_insert_sql(
|
|
rows=rows,
|
|
default_password=args.default_password,
|
|
email_domain=args.email_domain,
|
|
role=args.role,
|
|
status=args.status,
|
|
language=args.language,
|
|
)
|
|
|
|
output_path.parent.mkdir(parents=True, exist_ok=True)
|
|
output_path.write_text(sql, encoding="utf-8")
|
|
print(f"Generated SQL: {output_path}")
|
|
print(f"Rows parsed (including header): {len(rows)}")
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|