feat: 实现模板解析,自动识别 {{占位符}}

This commit is contained in:
MikiVL 2026-05-05 05:52:42 +08:00
parent 18de4f9f47
commit 1f51665e42
4 changed files with 62 additions and 2 deletions

View File

@ -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}

10
tests/create_fixtures.py Normal file
View File

@ -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")

BIN
tests/fixtures/sample_template.xlsx vendored Normal file

Binary file not shown.

View File

@ -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"