|
|
|
@ -33,16 +33,40 @@ def markdown_to_docx(markdown_text, output_file="report.docx"):
|
|
|
|
|
# 处理无序列表(- 或 *)
|
|
|
|
|
elif line.startswith("- ") or line.startswith("* "):
|
|
|
|
|
text = line.lstrip("-* ").strip()
|
|
|
|
|
doc.add_paragraph(text, style='List Bullet')
|
|
|
|
|
paragraph = doc.add_paragraph(style='List Bullet')
|
|
|
|
|
add_formatted_text(paragraph, text)
|
|
|
|
|
# 处理有序列表(1. 或 2.)
|
|
|
|
|
elif re.match(r"^\d+\. ", line):
|
|
|
|
|
text = re.sub(r"^\d+\. ", "", line).strip()
|
|
|
|
|
doc.add_paragraph(text, style='List Number')
|
|
|
|
|
paragraph = doc.add_paragraph(style='List Number')
|
|
|
|
|
add_formatted_text(paragraph, text)
|
|
|
|
|
# 处理普通段落
|
|
|
|
|
else:
|
|
|
|
|
if line.strip(): # 忽略空行
|
|
|
|
|
doc.add_paragraph(line.strip())
|
|
|
|
|
paragraph = doc.add_paragraph()
|
|
|
|
|
add_formatted_text(paragraph, line.strip())
|
|
|
|
|
|
|
|
|
|
# 保存 Word 文档
|
|
|
|
|
doc.save(output_file)
|
|
|
|
|
print(f"Word 文档已生成: {output_file}")
|
|
|
|
|
print(f"Word 文档已生成: {output_file}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def add_formatted_text(paragraph, text):
|
|
|
|
|
"""
|
|
|
|
|
将 Markdown 格式的文本添加到 Word 段落中,支持加粗语法(**xx**)
|
|
|
|
|
|
|
|
|
|
参数:
|
|
|
|
|
paragraph: Word 段落对象
|
|
|
|
|
text (str): 需要添加的文本
|
|
|
|
|
"""
|
|
|
|
|
# 使用正则表达式匹配加粗语法(**xx**)
|
|
|
|
|
parts = re.split(r"(\*\*.*?\*\*)", text)
|
|
|
|
|
for part in parts:
|
|
|
|
|
if part.startswith("**") and part.endswith("**"):
|
|
|
|
|
# 去掉 ** 并设置为加粗
|
|
|
|
|
bold_text = part[2:-2]
|
|
|
|
|
run = paragraph.add_run(bold_text)
|
|
|
|
|
run.bold = True
|
|
|
|
|
else:
|
|
|
|
|
# 普通文本
|
|
|
|
|
paragraph.add_run(part)
|