diff --git a/python/parser.py b/python/parser.py index fdffa2a..6737d44 100644 --- a/python/parser.py +++ b/python/parser.py @@ -1 +1,24 @@ -# placeholder +import re +from openpyxl import load_workbook + +PLACEHOLDER_RE = re.compile(r"\{\{(.+?)\}\}") + +def parse_template(file_path: str) -> dict: + wb = load_workbook(file_path, data_only=False) + sheets = wb.sheetnames + placeholders = [] + + for sheet_name in sheets: + ws = wb[sheet_name] + for row in ws.iter_rows(): + for cell in row: + if cell.value and isinstance(cell.value, str): + m = PLACEHOLDER_RE.search(cell.value) + if m: + placeholders.append({ + "name": m.group(1), + "sheet": sheet_name, + "cell": cell.coordinate, + }) + + return {"sheets": sheets, "placeholders": placeholders} diff --git a/tests/create_fixtures.py b/tests/create_fixtures.py new file mode 100644 index 0000000..671fdc4 --- /dev/null +++ b/tests/create_fixtures.py @@ -0,0 +1,10 @@ +from openpyxl import Workbook + +wb = Workbook() +ws = wb.active +ws.title = "Sheet1" +ws["B3"] = "{{编号}}" +ws["C5"] = "{{姓名}}" +ws["D7"] = "normal_value" # not a placeholder, should NOT be detected +wb.save("tests/fixtures/sample_template.xlsx") +print("fixture created") diff --git a/tests/fixtures/sample_template.xlsx b/tests/fixtures/sample_template.xlsx new file mode 100644 index 0000000..c6d220a Binary files /dev/null and b/tests/fixtures/sample_template.xlsx differ diff --git a/tests/python/test_parser.py b/tests/python/test_parser.py index fdffa2a..537fcfb 100644 --- a/tests/python/test_parser.py +++ b/tests/python/test_parser.py @@ -1 +1,28 @@ -# placeholder +import sys, os +sys.path.insert(0, os.path.join(os.path.dirname(__file__), "../../python")) + +from parser import parse_template + +FIXTURE = os.path.join(os.path.dirname(__file__), "../fixtures/sample_template.xlsx") + +def test_returns_sheets(): + result = parse_template(FIXTURE) + assert "sheets" in result + assert "Sheet1" in result["sheets"] + +def test_detects_placeholders(): + result = parse_template(FIXTURE) + names = [p["name"] for p in result["placeholders"]] + assert "编号" in names + assert "姓名" in names + +def test_ignores_non_placeholders(): + result = parse_template(FIXTURE) + names = [p["name"] for p in result["placeholders"]] + assert "normal_value" not in names + +def test_placeholder_has_cell_info(): + result = parse_template(FIXTURE) + biaohao = next(p for p in result["placeholders"] if p["name"] == "编号") + assert biaohao["sheet"] == "Sheet1" + assert biaohao["cell"] == "B3"