关于 office-to-md
office-to-md 是一项使用 markitdown 将 Office 等文件转换为 Markdown 的技能,适合整理文档以供搜索、版本管理或 AI 工作流使用,并按文件类型处理表格和幻灯片。
主要功能
- 01转换 Word、Excel、PowerPoint 和 PDF
- 02处理 HTML、图片、音频和 ZIP 文件
- 03将电子表格整理为 Markdown 表格
- 04将 PowerPoint 幻灯片分节
- 05支持图片 OCR 和音频转录
适用场景
- 01将 Office 文档转为可搜索的 Markdown
- 02把电子表格转换为表格文档
- 03提取 PDF 文本供后续处理
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ claude-office-skills/ skills --skill office-to-md安装后在 Claude Code 中输入/office-to-md确认已加载。
详细介绍
Office 转 Markdown 技能
概述
此技能使用 markitdown 将各种 Office 格式转换为 Markdown。markitdown 是 Microsoft 开源的文档转 Markdown 工具。它非常适合将 Office 内容转换为可搜索、可进行版本控制且适合 AI 处理的内容。
使用方法
- 提供 Office 文件(Word、Excel、PowerPoint、PDF 等)
- 可选:指定转换选项
- 我会将其转换为简洁的 Markdown
提示词示例:
- “将此 Word 文档转换为 Markdown”
- “将此 PowerPoint 转换为 Markdown 笔记”
- “将此 PDF 的内容提取为 Markdown”
- “将此 Excel 文件转换为 Markdown 表格”
领域知识
markitdown 基础知识
from markitdown import MarkItDown
# Initialize converter
md = MarkItDown()
# Convert file
result = md.convert("document.docx")
print(result.text_content)
# Save to file
with open("output.md", "w") as f:
f.write(result.text_content)
支持的格式
| 格式 | 扩展名 | 说明 |
|---|---|---|
| Word | .docx | 全文、表格、基本格式 |
| Excel | .xlsx | 转换为 Markdown 表格 |
| PowerPoint | .pptx | 将幻灯片转换为各个章节 |
| 文本提取 | ||
| HTML | .html | 简洁的 Markdown |
| 图像 | .jpg, .png | 使用视觉模型进行 OCR |
| 音频 | .mp3, .wav | 转录 |
| ZIP | .zip | 处理其中包含的文件 |
基本用法
Python API
from markitdown import MarkItDown
# Simple conversion
md = MarkItDown()
result = md.convert("document.docx")
# Access content
markdown_text = result.text_content
# With options
md = MarkItDown(
llm_client=None, # Optional LLM for enhanced processing
llm_model=None # Model name if using LLM
)
命令行
# Install
pip install markitdown
# Convert file
markitdown document.docx > output.md
# Or with output file
markitdown document.docx -o output.md
Word 文档转换
from markitdown import MarkItDown
md = MarkItDown()
# Convert Word document
result = md.convert("report.docx")
# Output preserves:
# - Headings (as # headers)
# - Bold/italic formatting
# - Lists (bulleted and numbered)
# - Tables (as markdown tables)
# - Hyperlinks
print(result.text_content)
输出示例:
# Annual Report 2024
## Executive Summary
This report summarizes the key achievements and challenges...
### Key Metrics
| Metric | 2023 | 2024 | Change |
|--------|------|------|--------|
| Revenue | $10M | $12M | +20% |
| Users | 50K | 75K | +50% |
## Detailed Analysis
The following sections provide...
Excel 转换
from markitdown import MarkItDown
md = MarkItDown()
result = md.convert("data.xlsx")
# Each sheet becomes a section
# Data becomes markdown tables
print(result.text_content)
输出示例:
## Sheet1
| Name | Department | Salary |
|------|------------|--------|
| John | Engineering | $80,000 |
| Jane | Marketing | $75,000 |
## Sheet2
| Product | Q1 | Q2 | Q3 | Q4 |
|---------|----|----|----|----|
| Widget A | 100 | 120 | 150 | 180 |
PowerPoint 转换
from markitdown import MarkItDown
md = MarkItDown()
result = md.convert("presentation.pptx")
# Each slide becomes a section
# Speaker notes included if present
print(result.text_content)
输出示例:
# Slide 1: Company Overview
Our mission is to...
## Key Points
- Innovation first
- Customer focused
- Global reach
---
# Slide 2: Market Analysis
The market opportunity is significant...
**Notes:** Mention the competitor analysis here
PDF 转换
from markitdown import MarkItDown
md = MarkItDown()
result = md.convert("document.pdf")
# Extracts text content
# Tables converted where detected
print(result.text_content)
图像转换(使用视觉模型)
from markitdown import MarkItDown
import anthropic
# Use Claude for image description
client = anthropic.Anthropic()
md = MarkItDown(
llm_client=client,
llm_model="claude-sonnet-4-20250514"
)
result = md.convert("diagram.png")
print(result.text_content)
# Output: Description of the image content
批量转换
from markitdown import MarkItDown
from pathlib import Path
def batch_convert(input_dir, output_dir):
"""Convert all Office files to Markdown."""
md = MarkItDown()
input_path = Path(input_dir)
output_path = Path(output_dir)
output_path.mkdir(exist_ok=True)
extensions = ['.docx', '.xlsx', '.pptx', '.pdf']
for ext in extensions:
for file in input_path.glob(f'*{ext}'):
try:
result = md.convert(str(file))
output_file = output_path / f"{file.stem}.md"
with open(output_file, 'w') as f:
f.write(result.text_content)
print(f"Converted: {file.name}")
except Exception as e:
print(f"Error converting {file.name}: {e}")
batch_convert('./documents', './markdown')
最佳实践
- 检查输出质量:检查转换后的 Markdown 是否准确
- 处理表格:复杂表格可能需要手动调整
- 保留结构:在源文档中使用一致的标题级别
- 处理图像:重要图像可考虑使用视觉模型
- 版本控制:将转换后的 Markdown 存储在 Git 中进行跟踪
常见模式
文档归档
import os
from datetime import datetime
from markitdown import MarkItDown
def archive_document(doc_path, archive_dir):
"""Convert and archive Office document to Markdown."""
md = MarkItDown()
result = md.convert(doc_path)
# Create archive structure
date_str = datetime.now().strftime('%Y-%m-%d')
filename = os.path.basename(doc_path)
base_name = os.path.splitext(filename)[0]
# Save with metadata
output_content = f"""---
source: {filename}
converted: {date_str}
---
{result.text_content}
"""
output_path = os.path.join(archive_dir, f"{base_name}.md")
with open(output_path, 'w') as f:
f.write(output_content)
return output_path
AI 就绪语料库
from markitdown import MarkItDown
from pathlib import Path
import json
def create_ai_corpus(doc_folder, output_file):
"""Convert documents to JSON corpus for AI training/RAG."""
md = MarkItDown()
corpus = []
for doc in Path(doc_folder).glob('**/*'):
if doc.suffix in ['.docx', '.pdf', '.pptx', '.xlsx']:
try:
result = md.convert(str(doc))
corpus.append({
'source': str(doc),
'filename': doc.name,
'content': result.text_content,
'type': doc.suffix[1:]
})
except Exception as e:
print(f"Skipped {doc.name}: {e}")
with open(output_file, 'w') as f:
json.dump(corpus, f, indent=2)
print(f"Created corpus with {len(corpus)} documents")
return corpus
示例
示例 1:转换文档套件
from markitdown import MarkItDown
from pathlib import Path
def convert_docs_to_wiki(docs_folder, wiki_folder):
"""Convert all Office docs to markdown wiki structure."""
md = MarkItDown()
docs_path = Path(docs_folder)
wiki_path = Path(wiki_folder)
# Create wiki structure
wiki_path.mkdir(exist_ok=True)
# Create index
index_content = "# Documentation Index\n\n"
for doc in sorted(docs_path.glob('**/*.docx')):
try:
result = md.convert(str(doc))
# Create relative path in wiki
rel_path = doc.relative_to(docs_path)
output_file = wiki_path / rel_path.with_suffix('.md')
output_file.parent.mkdir(parents=True, exist_ok=True)
# Write markdown
with open(output_file, 'w') as f:
f.write(result.text_content)
# Add to index
link = str(rel_path.with_suffix('.md')).replace('\\', '/')
index_content += f"- [{doc.stem}]({link})\n"
print(f"Converted: {doc.name}")
except Exception as e:
print(f"Error: {doc.name} - {e}")
# Write index
with open(wiki_path / 'index.md', 'w') as f:
f.write(index_content)
convert_docs_to_wiki('./company_docs', './wiki')
示例 2:会议笔记处理器
from markitdown import MarkItDown
import re
from datetime import datetime
def process_meeting_notes(pptx_path):
"""Extract and structure meeting notes from PowerPoint."""
md = MarkItDown()
result = md.convert(pptx_path)
# Parse the markdown
content = result.text_content
# Extract sections
sections = {
'attendees': [],
'agenda': [],
'decisions': [],
'action_items': []
}
current_section = None
for line in content.split('\n'):
line_lower = line.lower()
if 'attendee' in line_lower or 'participant' in line_lower:
current_section = 'attendees'
elif 'agenda' in line_lower:
current_section = 'agenda'
elif 'decision' in line_lower:
current_section = 'decisions'
elif 'action' in line_lower:
current_section = 'action_items'
elif line.strip().startswith(('-', '*', '•')) and current_section:
sections[current_section].append(line.strip()[1:].strip())
# Generate structured output
output = f"""# Meeting Notes
**Date:** {datetime.now().strftime('%Y-%m-%d')}
**Source:** {pptx_path}
## Attendees
{chr(10).join('- ' + a for a in sections['attendees'])}
## Agenda
{chr(10).join('- ' + a for a in sections['agenda'])}
## Decisions Made
{chr(10).join('- ' + d for d in sections['decisions'])}
## Action Items
{chr(10).join('- [ ] ' + a for a in sections['action_items'])}
"""
return output
notes = process_meeting_notes('team_meeting.pptx')
print(notes)
示例 3:将 Excel 转换为文档
from markitdown import MarkItDown
def excel_to_data_dictionary(xlsx_path):
"""Convert Excel data model to data dictionary documentation."""
md = MarkItDown()
result = md.convert(xlsx_path)
# Add documentation structure
doc = f"""# Data Dictionary
Generated from: `{xlsx_path}`
{result.text_content}
## Usage Notes
- All tables are derived from the source Excel file
- Review data types and constraints before use
- Contact data team for clarifications
## Change Log
| Date | Change | Author |
|------|--------|--------|
| {datetime.now().strftime('%Y-%m-%d')} | Initial generation | Auto |
"""
return doc
documentation = excel_to_data_dictionary('data_model.xlsx')
with open('data_dictionary.md', 'w') as f:
f.write(documentation)
限制
- 复杂格式可能会被简化
- 不会嵌入图像(可使用视觉模型生成描述)
- 部分表格结构可能无法完美转换
- 不会保留 Word 中的修订
- 可能无法提取批注
安装
pip install markitdown
# For image/audio processing
pip install markitdown[all]
# For specific features
pip install markitdown[images] # Image OCR
pip install markitdown[audio] # Audio transcription
资源
评论
支持 Markdown