Repository navigation
Expand file tree
/
Copy pathgenerate_docx.py
More file actions
154 lines (135 loc) · 4.57 KB
/
Copy pathgenerate_docx.py
File metadata and controls
154 lines (135 loc) · 4.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
将Markdown文档转换为Word文档
"""
from docx import Document
from docx.shared import Pt, RGBColor, Inches
from docx.enum.text import WD_ALIGN_PARAGRAPH
import re
def add_heading(doc, text, level):
"""添加标题"""
heading = doc.add_heading(text, level=level)
if level == 0:
heading.alignment = WD_ALIGN_PARAGRAPH.CENTER
def add_paragraph(doc, text, bold=False, font_size=12):
"""添加段落"""
p = doc.add_paragraph(text)
for run in p.runs:
run.font.size = Pt(font_size)
run.font.bold = bold
return p
def add_code_block(doc, code_text):
"""添加代码块"""
p = doc.add_paragraph(code_text)
p.style = 'No Spacing'
for run in p.runs:
run.font.name = 'Consolas'
run.font.size = Pt(10)
run.font.color.rgb = RGBColor(0, 0, 0)
# 设置段落背景色(灰色)
p.paragraph_format.line_spacing = 1.0
return p
def add_table_from_markdown(doc, table_lines):
"""从Markdown表格创建Word表格"""
# 解析表头
headers = [cell.strip() for cell in table_lines[0].split('|')[1:-1]]
# 解析数据行
rows_data = []
for line in table_lines[2:]: # 跳过表头和分隔符
if line.strip():
cells = [cell.strip() for cell in line.split('|')[1:-1]]
rows_data.append(cells)
# 创建表格
table = doc.add_table(rows=1 + len(rows_data), cols=len(headers))
table.style = 'Light Grid Accent 1'
# 填充表头
for i, header in enumerate(headers):
cell = table.rows[0].cells[i]
cell.text = header
for paragraph in cell.paragraphs:
for run in paragraph.runs:
run.font.bold = True
# 填充数据
for row_idx, row_data in enumerate(rows_data, start=1):
for col_idx, cell_data in enumerate(row_data):
table.rows[row_idx].cells[col_idx].text = cell_data
def parse_markdown_to_docx(md_file, docx_file):
"""解析Markdown并生成Word文档"""
doc = Document()
# 设置文档样式
style = doc.styles['Normal']
style.font.name = '微软雅黑'
style.font.size = Pt(12)
with open(md_file, 'r', encoding='utf-8') as f:
lines = f.readlines()
i = 0
in_code_block = False
code_lines = []
in_table = False
table_lines = []
while i < len(lines):
line = lines[i].rstrip()
# 代码块处理
if line.startswith('```'):
if in_code_block:
# 代码块结束
add_code_block(doc, '\n'.join(code_lines))
code_lines = []
in_code_block = False
else:
# 代码块开始
in_code_block = True
i += 1
continue
if in_code_block:
code_lines.append(line)
i += 1
continue
# 表格处理
if line.startswith('|') and '|' in line:
if not in_table:
table_lines = [line]
in_table = True
else:
table_lines.append(line)
i += 1
# 检查下一行是否还是表格
if i < len(lines) and not lines[i].strip().startswith('|'):
add_table_from_markdown(doc, table_lines)
table_lines = []
in_table = False
continue
# 标题处理
if line.startswith('#'):
level = len(re.match(r'^#+', line).group())
text = line.lstrip('#').strip()
add_heading(doc, text, level)
# 分隔线
elif line.strip() == '---':
doc.add_paragraph('_' * 50)
# 列表
elif line.startswith('- ') or line.startswith('* '):
text = line.lstrip('-* ').strip()
doc.add_paragraph(text, style='List Bullet')
# 普通段落
elif line.strip():
# 处理粗体 **text**
text = re.sub(r'\*\*(.*?)\*\*', r'\1', line)
# 处理代码 `code`
text = re.sub(r'`(.*?)`', r'\1', text)
# 处理链接 [text](url)
text = re.sub(r'\[(.*?)\]\(.*?\)', r'\1', text)
doc.add_paragraph(text)
else:
# 空行
doc.add_paragraph()
i += 1
# 保存文档
doc.save(docx_file)
print(f'✅ Word文档已生成: {docx_file}')
if __name__ == '__main__':
parse_markdown_to_docx(
'WMS自动化测试框架文档.md',
'WMS自动化测试框架文档.docx'
)