Description
Use Python'spython-docx、markdown、beautifulsoup4library to convert Markdown files into well-formatted Word documents. Supports conversion of Markdown elements such as headings, paragraphs, lists, tables, code blocks, images, etc.
Activation Conditions
Activate this skill when the user needs to convert a Markdown file into a Word document.
Skill Directory Structure
markdown-to-word-skill/
├── SKILL.md # 技能定义文件
├── README.md # 详细文档
├── requirements.txt # Python依赖
├── install.sh # 安装脚本
├── quick_start.sh # 快速开始脚本
├── scripts/
│ ├── md2docx.py # 主转换脚本
│ ├── md2docx_batch.py # 批量转换脚本
│ ├── md2docx_with_images.py # 带图片转换脚本
│ └── template_processor.py # 模板处理器
├── templates/
│ ├── academic.docx # 学术论文模板
│ ├── business.docx # 商业报告模板
│ └── technical.docx # 技术文档模板
├── examples/
│ ├── sample.md # 示例Markdown文件
│ ├── sample_output.docx # 示例输出
│ └── test_images/ # 测试图片目录
└── config/
└── styles.json # 样式配置
Core Features
1. Basic Conversion
- Convert Markdown files to Word documents
- Support all basic Markdown syntax
- Preserve document structure and formatting
2. Advanced Features
- Image Processing: Automatically insert images and adjust size
- Table Conversion: Convert Markdown tables to Word tables
- Code Blocks: Preserve code formatting and syntax highlighting
- Mathematical Formulas: Support LaTeX mathematical formulas
- Custom Styles: Apply predefined or custom styles
3. Batch Processing
- Batch convert multiple Markdown files
- Support recursive folder processing
- Generate progress reports
4. Template System
- Use predefined templates (academic, business, technical)
- Custom template support
- Automatically apply styles
Dependency Installation
Python Dependencies
pip install python-docx markdown beautifulsoup4 pillow
System Dependencies (Optional)
# Ubuntu/Debian
sudo apt-get install python3-pip python3-venv
# macOS
brew install python3
Usage
1. Basic Conversion
python scripts/md2docx.py --input sample.md --output sample.docx
2. Use a Template
python scripts/md2docx.py --input sample.md --output sample.docx --template templates/academic.docx
3. Batch Conversion
python scripts/md2docx_batch.py --input-dir ./markdown_files --output-dir ./word_docs
4. Convert with Images
python scripts/md2docx_with_images.py --input sample.md --output sample.docx --image-dir ./images
Script Explanation
md2docx.py - Main conversion script
"""
Markdown转Word主转换脚本
支持:
- 标题(H1-H6)
- 段落和文本格式(粗体、斜体、删除线)
- 列表(有序、无序)
- 表格
- 代码块
- 引用块
- 水平线
- 图片
- 链接
"""
# 基本用法
python md2docx.py --input input.md --output output.docx
# 高级选项
python md2docx.py --input input.md --output output.docx \
--template academic.docx \
--style-title "Title" \
--style-heading1 "Heading 1" \
--style-heading2 "Heading 2" \
--style-paragraph "Normal" \
--style-code "Code" \
--style-quote "Quote"
md2docx_batch.py - Batch conversion script
"""
批量转换脚本
支持:
- 批量处理文件夹中的所有Markdown文件
- 递归处理子文件夹
- 保持目录结构
- 生成转换报告
"""
# 基本用法
python md2docx_batch.py --input-dir ./docs --output-dir ./word_docs
# 高级选项
python md2docx_batch.py --input-dir ./docs --output-dir ./word_docs \
--recursive \
--template technical.docx \
--report report.json \
--skip-existing
md2docx_with_images.py - Conversion script with images
"""
带图片处理的转换脚本
支持:
- 自动查找并插入图片
- 图片大小调整
- 图片居中/对齐
- 图片标题
- 相对路径支持
"""
# 基本用法
python md2docx_with_images.py --input article.md --output article.docx --image-dir ./images
# 高级选项
python md2docx_with_images.py --input article.md --output article.docx \
--image-dir ./images \
--image-width 500 \
--image-height 300 \
--image-quality 85 \
--add-captions
Supported Markdown Elements
1. Headings
# 一级标题
## 二级标题
### 三级标题
2. Text Formatting
**粗体文本**
*斜体文本*
~~删除线文本~~
3. Lists
- 无序列表项1
- 无序列表项2
1. 有序列表项1
2. 有序列表项2
4. Tables
| 列1 | 列2 | 列3 |
|-----|-----|-----|
| 数据1 | 数据2 | 数据3 |
| 数据4 | 数据5 | 数据6 |
5. Code Blocks
```python
def hello_world():
print("Hello, World!")
```
6. Images

7. Links
[链接文本](https://example.com)
8. Blockquotes
> 这是一段引用文字
> 可以有多行
9. Horizontal Rules
---
Style Configuration
Default Style Mapping
{
"h1": "Heading 1",
"h2": "Heading 2",
"h3": "Heading 3",
"h4": "Heading 4",
"h5": "Heading 5",
"h6": "Heading 6",
"p": "Normal",
"code": "Code",
"quote": "Quote",
"table": "Table Grid",
"image": "Image Caption"
}
Custom Styles
Create config/styles.json:
{
"styles": {
"title": "自定义标题",
"heading1": "自定义标题1",
"heading2": "自定义标题2",
"paragraph": "自定义段落",
"code": "代码样式",
"quote": "引用样式"
},
"font": {
"title": {"name": "微软雅黑", "size": 24, "bold": true},
"heading1": {"name": "微软雅黑", "size": 18, "bold": true},
"paragraph": {"name": "宋体", "size": 12}
},
"colors": {
"title": "2E74B5",
"heading1": "2E74B5",
"code_background": "F2F2F2"
}
}
Template System
Predefined Templates
-
academic.docx - Academic Paper Template
- Compliant with academic paper formatting
- Includes abstract, keywords, references
- Supports chapter numbering
-
business.docx - Business Report Template
- Professional business style
- Includes company logo, header and footer
- Chart and table styles
-
technical.docx - Technical Documentation Template
- Code-friendly formatting
- Technical diagram support
- API documentation style
Create a Custom Template
- Create a template document in Word
- Define styles (headings, paragraphs, code, etc.)
- Save as a
.docxfile to thetemplates/directory - Use the
--templateparameter to specify
Installation Script
install.sh
#!/bin/bash
# Markdown转Word技能安装脚本
echo "安装Markdown转Word技能..."
# 创建虚拟环境
python3 -m venv venv
source venv/bin/activate
# 安装Python依赖
pip install python-docx markdown beautifulsoup4 pillow
# 创建必要目录
mkdir -p templates examples test_images config
echo "✅ 安装完成!"
echo "激活虚拟环境:source venv/bin/activate"
echo "运行测试:python scripts/md2docx.py --input examples/sample.md --output examples/sample_output.docx"
quick_start.sh
#!/bin/bash
# 快速开始脚本
echo "Markdown转Word技能快速开始..."
# 检查虚拟环境
if [ ! -d "venv" ]; then
echo "创建虚拟环境..."
python3 -m venv venv
fi
# 激活虚拟环境
source venv/bin/activate
# 安装依赖
pip install -q python-docx markdown beautifulsoup4 pillow
# 运行示例
echo "运行示例转换..."
python scripts/md2docx.py --input examples/sample.md --output examples/sample_output.docx
if [ $? -eq 0 ]; then
echo "✅ 示例转换成功!"
echo "输出文件:examples/sample_output.docx"
else
echo "❌ 转换失败,请检查错误信息"
fi
Example Files
sample.md
# 示例文档
这是一个Markdown转Word的示例文档。
## 章节1:介绍
这是第一章节的内容。**粗体文本**和*斜体文本*都可以正常转换。
### 子章节1.1
这是一个子章节。
## 章节2:列表示例
### 无序列表
- 项目1
- 项目2
- 子项目2.1
- 子项目2.2
- 项目3
### 有序列表
1. 第一步
2. 第二步
3. 第三步
## 章节3:表格示例
| 姓名 | 年龄 | 职业 |
|------|------|------|
| 张三 | 25 | 工程师 |
| 李四 | 30 | 设计师 |
| 王五 | 28 | 产品经理 |
## 章节4:代码示例
```python
def calculate_sum(a, b):
"""计算两个数的和"""
return a + b
result = calculate_sum(10, 20)
print(f"结果: {result}")
Chapter 5: Blockquote Example
This is quoted content and can have multiple lines
— Quote Source
Chapter 6: Image Example

End of document.
## 故障排除
### 常见问题
#### 1. 缺少依赖
ModuleNotFoundError: No module named 'docx'
**解决方案**:
```bash
pip install python-docx
2. Incorrect image path
FileNotFoundError: [Errno 2] No such file or directory: 'image.jpg'
Solution:
- Use an absolute path
- Use
--image-dirparameter to specify the image directory - Ensure the image file exists
3. Style does not exist
KeyError: 'Heading 1'
Solution:
- Check the style name in the template file
- Use
--list-stylesto view available styles - Create a custom style configuration
4. Encoding issues
UnicodeDecodeError: 'utf-8' codec can't decode byte...
Solution:
python md2docx.py --input input.md --output output.docx --encoding utf-8-sig
Debug mode
python md2docx.py --input input.md --output output.docx --debug
Usage in OpenClaw
As a standalone skill
# 转换单个文件
exec("cd /path/to/markdown-to-word-skill && python scripts/md2docx.py --input document.md --output document.docx")
# 批量转换
exec("cd /path/to/markdown-to-word-skill && python scripts/md2docx_batch.py --input-dir ./docs --output-dir ./word_docs")
Integrate in a skill
def convert_markdown_to_word(md_file, docx_file, template=None):
"""转换Markdown到Word"""
import subprocess
cmd = ["python", "scripts/md2docx.py", "--input", md_file, "--output", docx_file]
if template:
cmd.extend(["--template", template])
result = subprocess.run(cmd, capture_output=True, text=True)
if result.returncode == 0:
return {"success": True, "output": docx_file}
else:
return {"success": False, "error": result.stderr}
Performance optimization
1. Batch processing optimization
- Use multiprocessing to handle large files
- Memory optimization
- Cache parsed templates
2. Image processing optimization
- Image compression
- Thumbnail generation
- Parallel processing
3. Style caching
- Cache style definitions
- Reduce repetitive operations
- Improve conversion speed
Extended features
1. Custom converter
from md2docx import MarkdownToDocx
class CustomConverter(MarkdownToDocx):
def convert_custom_element(self, element):
"""处理自定义Markdown元素"""
pass
2. Plugin system
# 创建插件
class ImagePlugin:
def process(self, converter, element):
"""处理图片元素"""
pass
# 注册插件
converter.register_plugin(ImagePlugin())
3. Web API
from flask import Flask, request, send_file
app = Flask(__name__)
@app.route('/convert', methods=['POST'])
def convert():
md_content = request.form['markdown']
# 转换逻辑
return send_file('output.docx')
Changelog
v1.0.0 (2026-03-02)
- Initial version release
- Support conversion of basic Markdown elements
- Add image processing functionality
- Implement batch conversion
- Add template system
Contribution guidelines
- Fork the project
- Create a feature branch
- Commit changes
- Push to the branch
- Create a Pull Request
License
MIT License
Contact information
- Issue feedback: create a GitHub Issue
- Feature suggestions: submit a Pull Request
- Documentation improvements: edit README.md
Skill creation time:2026-03-02 10:12 GMT+8 Creator:OpenClaw AI Assistant Version:1.0.0