Skip to content

Commit f2d3fa4

Browse files
committed
Update dependencies in pyproject.toml, increment version to 2.12.3 in version.py, and add xlsx.py for Excel file handling functions.
1 parent b9fdd0f commit f2d3fa4

3 files changed

Lines changed: 84 additions & 1 deletion

File tree

pyproject.toml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,8 @@ dependencies = [
5252
"wath>=1.1.6",
5353
"waveforms>=1.9.4",
5454
"rich>=14.0.0",
55+
"pydantic>=2.12.5",
56+
"openpyxl>=3.1.5",
5557
]
5658
dynamic = ["version"]
5759

qulab/tools/xlsx.py

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
from openpyxl import load_workbook
2+
3+
4+
def read_excel_to_dict(path: str) -> dict[str, list[dict[str, str]]]:
5+
wb = load_workbook(path, read_only=True, data_only=True)
6+
result = {}
7+
8+
for ws in wb.worksheets:
9+
sheet_data = []
10+
11+
rows = list(ws.iter_rows(values_only=True))
12+
13+
if not rows:
14+
result[ws.title] = []
15+
continue
16+
17+
header_row = rows[0]
18+
19+
# 过滤掉空列名
20+
valid_indices = [
21+
idx for idx, col in enumerate(header_row)
22+
if col is not None and str(col).strip() != ""
23+
]
24+
25+
headers = [str(header_row[i]).strip() for i in valid_indices]
26+
27+
# 读取数据行
28+
for row in rows[1:]:
29+
row_dict = {}
30+
for col_idx, header in zip(valid_indices, headers):
31+
value = row[col_idx] if col_idx < len(row) else None
32+
row_dict[header] = "" if value is None else str(value)
33+
sheet_data.append(row_dict)
34+
35+
result[ws.title] = sheet_data
36+
37+
wb.close()
38+
return result
39+
40+
41+
def update_cells(path: str, sheet_name: str, updates: dict[str, str]):
42+
"""
43+
updates 示例:
44+
{
45+
"A2": "新内容",
46+
"C5": "修改值",
47+
}
48+
"""
49+
50+
wb = load_workbook(path, keep_vba=True)
51+
ws = wb[sheet_name]
52+
53+
for cell_addr, new_value in updates.items():
54+
ws[cell_addr].value = new_value # 只改 value
55+
56+
wb.save(path)
57+
wb.close()
58+
59+
60+
def update_by_key(path, sheet_name, key_col, key_value, target_col, new_value):
61+
"""
62+
找到 key_col 的值为 key_value 的行,将该行 target_col 的值改为 new_value
63+
key_col 和 target_col 都是列名
64+
"""
65+
wb = load_workbook(path, keep_vba=True)
66+
ws = wb[sheet_name]
67+
68+
# 找列号
69+
header = [cell.value for cell in ws[1]]
70+
71+
key_idx = header.index(key_col) + 1
72+
target_idx = header.index(target_col) + 1
73+
74+
for row in ws.iter_rows(min_row=2):
75+
# 找到对应的行
76+
if row[key_idx - 1].value == key_value:
77+
ws.cell(row=row[0].row, column=target_idx).value = new_value
78+
break
79+
80+
wb.save(path)
81+
wb.close()

qulab/version.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
__version__ = "2.12.2"
1+
__version__ = "2.12.3"

0 commit comments

Comments
 (0)