
Office Automation
- 3k installs
- 6 repo stars
- Updated February 22, 2026
- texiaoyao/office-automation-skill
office-automation is a skill that runs Python scripts to read, write, fill templates, and analyze Word and Excel files so agents can automate document and spreadsheet workflows.
About
office-automation is a texiaoyao skill that automates Word and Excel file handling through Python scripts in skills/office-automation/scripts using python-docx, openpyxl, and pandas. Installation requires pip install python-docx openpyxl pandas and python3 on PATH per OpenClaw metadata. word_processor.py exposes read, write, template fill with JSON data replacing variables, extract tables to CSV, and format commands for .docx files only. excel_processor.py covers read with sheet selection, write from JSON data, merge of multiple workbooks, convert between Excel and CSV, and analyze with pivot-style statistics. Documented scenarios include batch report generation, template contract filling, table extraction, data merging, and format conversion. Notes specify .docx only for Word, .xlsx and .xlsm for Excel, UTF-8 encoding, and batching files over 100MB. Developers reach for office-automation when agents must replace manual spreadsheet and document copy-paste with repeatable CLI-driven office file workflows.
- word_processor.py: read, write, template, extract, and format commands for .docx.
- excel_processor.py: read, write, merge, convert, and analyze commands for Excel files.
- Depends on python-docx, openpyxl, and pandas installed via pip.
- Template fill replaces variables with JSON --data payloads.
- Supports batch merges, CSV extraction, and UTF-8 encoded outputs.
Office Automation by the numbers
- 2,968 all-time installs (skills.sh)
- +5 installs in the week ending Aug 4, 2026 (Skillselion tracking)
- Ranked #152 of 2,715 Automation & Workflows skills by installs in the Skillselion catalog
- Security screen: MEDIUM risk (skills.sh audit)
- Data as of Aug 4, 2026 (Skillselion catalog sync)
office-automation capabilities & compatibility
- Capabilities
- read and write .docx word documents · fill templates with json variable substitution · read, write, merge, and convert excel workbooks · extract docx tables and run excel analysis comma
What office-automation says it does
使用 Python 脚本自动化处理 Word (.docx) 和 Excel (.xlsx/xlsm) 文件。
pip install python-docx openpyxl pandas
template doc.docx --data '{"key": "value"}'
npx skills add https://github.com/texiaoyao/office-automation-skill --skill office-automationAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 3k |
|---|---|
| repo stars | ★ 6 |
| Security audit | 3 / 3 scanners passed |
| Last updated | February 22, 2026 |
| Repository | texiaoyao/office-automation-skill ↗ |
How do I batch-generate Word reports, fill Excel templates, or merge spreadsheets without manual copy-paste?
Automate Word and Excel read, write, template fill, merge, and analysis tasks with Python CLI scripts.
Who is it for?
Teams automating recurring Word and Excel tasks with Python when .docx and .xlsx files are the source and destination formats.
Skip if: Skip for legacy .doc-only files, GUI macro recording, or workloads needing real-time collaborative editing instead of file scripts.
When should I use this skill?
User asks to read or write Word or Excel files, fill a document template, merge spreadsheets, or convert Excel to CSV.
What you get
Formatted .docx or .xlsx outputs, extracted CSV tables, merged workbooks, or analysis results from CLI script commands.
- Generated documents
- Merged spreadsheets
- Extracted CSV data
By the numbers
- Requires 3 Python packages: python-docx, openpyxl, pandas
- Supports Word .docx and Excel .xlsx/.xlsm file formats
Files
Office 自动化技能
使用 Python 脚本自动化处理 Word (.docx) 和 Excel (.xlsx/xlsm) 文件。
快速开始
1. 安装依赖
pip install python-docx openpyxl pandas2. 基本用法
处理 Word 文档:
python scripts/word_processor.py read document.docx
python scripts/word_processor.py write output.docx --content "Hello World"
python scripts/word_processor.py template fill.docx --data '{"name": "张三", "date": "2026-02-22"}'处理 Excel 表格:
python scripts/excel_processor.py read data.xlsx
python scripts/excel_processor.py write output.xlsx --sheet "Sheet1"
python scripts/excel_processor.py merge folder/ --output merged.xlsx---
脚本说明
word_processor.py
| 命令 | 说明 | 示例 |
|---|---|---|
read | 读取 Word 文档内容 | read file.docx |
write | 创建新文档 | write out.docx --content "文本" |
template | 填充模板(替换 {{变量}}) | template doc.docx --data '{"key": "value"}' |
extract | 提取表格到 CSV | extract file.docx --table 1 |
format | 格式化文档 | format file.docx --style heading |
excel_processor.py
| 命令 | 说明 | 示例 |
|---|---|---|
read | 读取 Excel 数据 | read data.xlsx --sheet Sheet1 |
write | 写入数据到 Excel | write out.xlsx --data data.json |
merge | 合并多个 Excel 文件 | merge folder/ --output all.xlsx |
convert | Excel ↔ CSV 转换 | convert file.xlsx --to csv |
analyze | 数据分析(统计、透视) | analyze sales.xlsx --pivot |
---
使用场景
Word 处理
- 📝 批量生成报告/合同
- 📋 填充模板文档
- 📊 提取文档中的表格数据
- 🎨 统一文档格式
Excel 处理
- 📈 数据汇总和合并
- 🔄 格式转换(Excel ↔ CSV)
- 📊 数据分析和统计
- 📋 批量处理多个表格
---
注意事项
1. Word 格式:仅支持 .docx 格式(不支持旧版 .doc) 2. Excel 格式:支持 .xlsx 和 .xlsm 3. 编码:默认使用 UTF-8 编码 4. 大文件:超过 100MB 的文件建议分批次处理
---
脚本位置
所有脚本位于 skills/office-automation/scripts/ 目录。
使用时请确保从技能目录或 workspace 根目录运行。
# Python
__pycache__/
*.py[cod]
*$py.class
*.so
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg
# Virtual Environment
venv/
env/
ENV/
.venv
# IDE
.vscode/
.idea/
*.swp
*.swo
*~
# OS
.DS_Store
Thumbs.db
# Generated output
*.docx
*.xlsx
*.csv
!examples/
# Test files
test_*.py
*_test.py
.pytest_cache/
.coverage
htmlcov/
# Logs
*.log
# Secrets
.env
.env.local
*.key
*.pem
# Temporary files
tmp/
temp/
*.tmp
Changelog
All notable changes to this project will be documented in this file.
[1.0.0] - 2026-02-22
Added
- Initial release of Office Automation Skill
- Word document processing (
word_processor.py) - Read document content and structure
- Create new documents with title and content
- Template filling with JSON data
- Extract tables to CSV format
- Excel spreadsheet processing (
excel_processor.py) - Read single or multiple sheets
- Write data with custom headers
- Merge multiple Excel files
- Convert between Excel and CSV formats
- Basic data analysis (statistics, missing values)
- Batch processing utilities (
batch_processor.py) - Batch template filling for mass document generation
- Batch format conversion (Excel ↔ CSV)
- Batch table extraction from Word documents
- Documentation
- Complete usage guide (使用指南.md)
- Example collection (示例集合.md)
- API reference (office_api.md)
- Bilingual README (Chinese/English)
- Example files
- Sample JSON data for testing
- Template examples
- GitHub ready files
- MIT License
- .gitignore for Python projects
- Changelog
Dependencies
- python-docx >= 0.8.11
- openpyxl >= 3.0.0
- pandas >= 1.3.0
Compatibility
- Python 3.8+
- OpenClaw 2026.2+
- Windows, macOS, Linux
Office 自动化技能 - 完整使用指南
📖 目录
1. 安装与配置 2. Word 文档处理 3. Excel 表格处理 4. 批量处理 5. 实战案例 6. 常见问题
---
安装与配置
环境要求
- Python 3.8+
- pip 包管理器
安装依赖
# 进入技能目录
cd /Users/bbaa/.openclaw/workspace/skills/office-automation
# 安装 Python 库
pip install python-docx openpyxl pandas
# 验证安装
python -c "import docx, openpyxl, pandas; print('✓ 所有依赖已安装')"验证脚本
# 测试 Word 脚本
python scripts/word_processor.py --help
# 测试 Excel 脚本
python scripts/excel_processor.py --help
# 测试批量处理脚本
python scripts/batch_processor.py --help---
Word 文档处理
读取文档
# 读取完整文档内容
python scripts/word_processor.py read report.docx
# 输出格式(JSON)
{
"paragraphs": [
{"index": 0, "text": "标题内容", "style": "Heading 1"},
{"index": 1, "text": "正文内容", "style": "Normal"}
],
"tables": [
{"index": 0, "rows": 5, "cols": 3, "data": [...]}
],
"sections": 1
}创建文档
# 创建简单文档
python scripts/word_processor.py write output.docx \
--content "这是第一段内容。
这是第二段内容。" \
--title "文档标题"
# 创建带格式的文档(使用 Python API)
python << 'EOF'
from docx import Document
doc = Document()
doc.add_heading('报告标题', 0)
doc.add_heading('第一章', 1)
doc.add_paragraph('正文内容...')
doc.save('report.docx')
print('✓ 文档已创建')
EOF模板填充
步骤 1:创建模板
在 Word 文档中使用 {{变量名}} 格式:
会议邀请函
尊敬的 {{name}} {{position}}:
诚邀您参加 {{event_name}} 活动。
时间:{{event_date}}
地点:{{event_location}}
{{company_name}}
{{date}}步骤 2:准备数据
[
{
"name": "张三",
"position": "经理",
"event_name": "2026 年度产品发布会",
"event_date": "2026 年 3 月 15 日",
"event_location": "北京国际会议中心",
"company_name": "科技有限公司",
"date": "2026 年 2 月 22 日",
"filename": "邀请函_张三.docx"
}
]步骤 3:执行填充
# 单个文件
python scripts/word_processor.py template invitation.docx \
--output invitation_filled.docx \
--data '{"name":"张三","position":"经理"}'
# 批量填充
python scripts/batch_processor.py templates \
--folder ./output \
--template invitation.docx \
--data attendees.json提取表格
# 提取所有表格
python scripts/word_processor.py extract report.docx --output-dir ./tables
# 提取指定表格(索引从 0 开始)
python scripts/word_processor.py extract report.docx --table 0 --output-dir ./tables
# 输出:report_table_0.csv, report_table_1.csv, ...---
Excel 表格处理
读取数据
# 读取所有工作表
python scripts/excel_processor.py read data.xlsx
# 读取指定工作表
python scripts/excel_processor.py read data.xlsx --sheet "销售数据"
# 输出格式(JSON)
{
"file": "data.xlsx",
"sheets": {
"Sheet1": {
"rows": 100,
"cols": 5,
"data": [["姓名","年龄","城市"], ["张三",25,"北京"], ...]
}
},
"sheet_names": ["Sheet1", "Sheet2"]
}创建表格
# 从 JSON 数据创建
python scripts/excel_processor.py write output.xlsx \
--data '[["姓名","年龄","城市"],["张三",25,"北京"],["李四",30,"上海"]]' \
--headers "姓名,年龄,城市" \
--sheet "员工列表"合并文件
# 合并文件夹中所有 Excel 文件
python scripts/excel_processor.py merge ./monthly_reports/ \
--output yearly_report.xlsx \
--sheet "全年汇总"
# 支持的文件格式:.xlsx, .xlsm格式转换
# Excel 转 CSV(每个工作表生成一个 CSV)
python scripts/excel_processor.py convert data.xlsx --to csv
# CSV 转 Excel
python scripts/excel_processor.py convert data.csv --to xlsx --output data.xlsx数据分析
# 基础分析
python scripts/excel_processor.py analyze sales.xlsx
# 输出包含:
# - 行数、列数
# - 数据类型
# - 缺失值统计
# - 数值列统计(均值、标准差、最小值、最大值等)---
批量处理
批量填充模板
python scripts/batch_processor.py templates \
--folder ./generated_docs \
--template contract_template.docx \
--data contracts.json批量格式转换
# Excel 转 CSV
python scripts/batch_processor.py convert \
--folder ./excel_files \
--from xlsx \
--to csv \
--output ./csv_files
# CSV 转 Excel
python scripts/batch_processor.py convert \
--folder ./csv_files \
--from csv \
--to xlsx \
--output ./excel_files批量提取表格
python scripts/batch_processor.py extract \
--folder ./reports \
--output ./extracted_tables---
实战案例
案例 1:批量生成合同
场景:需要为 100 个客户生成个性化合同
步骤:
1. 创建合同模板 contract_template.docx:
合同编号:{{contract_no}}
甲方:{{party_a}}
乙方:{{party_b}}
合同金额:{{amount}} 元
签订日期:{{sign_date}}2. 准备客户数据 clients.json:
[
{
"contract_no": "HT2026001",
"party_a": "甲公司",
"party_b": "乙公司",
"amount": "100000",
"sign_date": "2026-02-22",
"filename": "合同_HT2026001.docx"
}
]3. 执行批量生成:
python scripts/batch_processor.py templates \
--folder ./contracts \
--template contract_template.docx \
--data clients.json案例 2:月度报告合并
场景:合并 12 个月的销售报告
# 假设文件夹结构:
# ./monthly_reports/
# ├── 2025-01.xlsx
# ├── 2025-02.xlsx
# └── ...
python scripts/excel_processor.py merge ./monthly_reports/ \
--output 2025_annual_report.xlsx \
--sheet "全年汇总"案例 3:数据提取与分析
场景:从 Word 报告中提取表格数据并分析
# 1. 提取表格
python scripts/word_processor.py extract quarterly_report.docx \
--output-dir ./tables
# 2. 使用 pandas 分析(Python 脚本)
python << 'EOF'
import pandas as pd
# 读取提取的 CSV
df = pd.read_csv('tables/quarterly_report_table_0.csv')
print(df.describe())
df.to_excel('analysis_result.xlsx', index=False)
EOF---
常见问题
Q1: 中文乱码怎么办?
A: CSV 文件使用 UTF-8-BOM 编码,可直接用 Excel 打开:
# 脚本已自动处理编码,无需额外配置Q2: 支持旧版 .doc 格式吗?
A: 不支持。需要先用 Word 另存为 .docx 格式。
Q3: 如何处理超大文件(>100MB)?
A: 使用分块处理:
import pandas as pd
# 分块读取 Excel
for chunk in pd.read_excel('large_file.xlsx', chunksize=10000):
process(chunk)Q4: 模板变量不匹配怎么办?
A: 检查变量格式,必须是 {{变量名}}(双花括号),且与 JSON 数据中的 key 完全一致。
Q5: 如何保留 Excel 中的公式?
A: openpyxl 可以读取公式结果,但不会重新计算公式。如需保留公式,使用 data_only=False:
from openpyxl import load_workbook
wb = load_workbook('file.xlsx', data_only=False)Q6: 脚本执行报错 "ModuleNotFoundError"?
A: 确保已安装依赖:
pip install python-docx openpyxl pandas---
高级用法
自定义 Python 脚本
基于现有脚本扩展功能:
#!/usr/bin/env python3
from docx import Document
from openpyxl import Workbook
# 创建 Word 报告
doc = Document()
doc.add_heading('销售报告', 0)
# 从 Excel 读取数据
import pandas as pd
df = pd.read_excel('sales.xlsx')
# 添加表格
table = doc.add_table(rows=len(df)+1, cols=len(df.columns))
for i, col in enumerate(df.columns):
table.cell(0, i).text = col
for i, row in df.iterrows():
for j, val in enumerate(row):
table.cell(i+1, j).text = str(val)
doc.save('sales_report.docx')与 OpenClaw 集成
在聊天中直接使用:
请帮我读取 sales_report.docx 并总结主要内容
从 data.xlsx 提取 Q4 销售数据,生成柱状图
批量生成 50 份邀请函,数据在 attendees.json 中---
技术支持
- 📧 问题反馈:查看 GitHub Issues
- 📚 更多文档:references/office_api.md
- 💬 社区讨论:OpenClaw Discord
Office 自动化 - 示例集合
本目录包含常用场景的完整示例代码和数据模板。
---
📄 Word 示例
示例 1:会议通知模板
模板文件结构:
会议通知
{{meeting_title}}
时间:{{meeting_time}}
地点:{{meeting_location}}
主持人:{{host_name}}
参会人员:
{{attendees}}
会议议程:
{{agenda}}
{{company_name}}
{{notice_date}}数据文件 (meeting.json):
[
{
"meeting_title": "2026 年第一季度战略规划会议",
"meeting_time": "2026 年 3 月 1 日 上午 9:00",
"meeting_location": "公司会议室 A",
"host_name": "张总经理",
"attendees": "各部门负责人、项目经理",
"agenda": "1. 上年度总结\n2. 本年度目标\n3. 资源分配",
"company_name": "科技有限公司",
"notice_date": "2026 年 2 月 22 日",
"filename": "会议通知_001.docx"
}
]执行命令:
python scripts/batch_processor.py templates \
--folder ./output \
--template meeting_notice.docx \
--data meeting.json---
示例 2:员工入职文档
模板变量:
员工入职通知书
姓名:{{employee_name}}
部门:{{department}}
职位:{{position}}
入职日期:{{start_date}}
直属上级:{{manager_name}}
薪资信息:
- 基本工资:{{base_salary}} 元
- 绩效工资:{{performance_salary}} 元
报到地点:{{location}}
联系人:{{contact_person}}
联系电话:{{contact_phone}}数据文件 (new_hires.json):
[
{
"employee_name": "李明",
"department": "技术部",
"position": "高级开发工程师",
"start_date": "2026 年 3 月 1 日",
"manager_name": "王技术总监",
"base_salary": "25000",
"performance_salary": "5000",
"location": "北京市朝阳区 XX 大厦 10 层",
"contact_person": "HR 刘女士",
"contact_phone": "010-12345678",
"filename": "入职通知_李明.docx"
}
]---
示例 3:项目报告模板
模板结构:
项目周报
项目名称:{{project_name}}
报告周期:{{report_period}}
项目经理:{{project_manager}}
一、本周完成情况
{{completed_tasks}}
二、下周计划
{{next_week_plan}}
三、风险与问题
{{risks_and_issues}}
四、资源需求
{{resource_needs}}---
📊 Excel 示例
示例 1:销售数据表
创建销售数据表:
python scripts/excel_processor.py write sales_data.xlsx \
--data '[
["日期","产品","销售额","数量","区域"],
["2026-01-01","产品 A",15000,100,"华北"],
["2026-01-01","产品 B",22000,80,"华东"],
["2026-01-02","产品 A",18000,120,"华北"],
["2026-01-02","产品 B",25000,90,"华东"]
]' \
--headers "日期,产品,销售额,数量,区域" \
--sheet "销售明细"分析销售数据:
python scripts/excel_processor.py analyze sales_data.xlsx---
示例 2:员工考勤表
数据结构:
[
["员工 ID","姓名","部门","1 日","2 日","3 日","4 日","5 日","出勤率"],
["E001","张三","技术部","√","√","√","√","√","100%"],
["E002","李四","市场部","√","×","√","√","√","80%"],
["E003","王五","技术部","√","√","○","√","√","90%"]
]说明:√ = 出勤,× = 缺勤,○ = 请假
---
示例 3:财务报表模板
多工作表结构:
# 创建包含多个工作表的 Excel 文件
python << 'EOF'
from openpyxl import Workbook
wb = Workbook()
# 工作表 1:收入明细
ws1 = wb.active
ws1.title = "收入明细"
ws1.append(["日期", "项目", "金额", "备注"])
ws1.append(["2026-01-01", "销售收入", 100000, "Q1"])
ws1.append(["2026-01-15", "服务收入", 50000, "咨询费"])
# 工作表 2:支出明细
ws2 = wb.create_sheet("支出明细")
ws2.append(["日期", "项目", "金额", "备注"])
ws2.append(["2026-01-05", "办公费用", 20000, "办公用品"])
ws2.append(["2026-01-20", "人力成本", 80000, "工资"])
# 工作表 3:汇总
ws3 = wb.create_sheet("汇总")
ws3.append(["项目", "金额"])
ws3.append(["总收入", 150000])
ws3.append(["总支出", 100000])
ws3.append(["净利润", 50000])
wb.save('financial_report.xlsx')
print('✓ 财务报表已创建')
EOF---
示例 4:库存管理表
数据结构:
[
["SKU","产品名称","类别","当前库存","安全库存","单价","供应商"],
["P001","产品 A","电子",150,100,299,"供应商 A"],
["P002","产品 B","服装",80,50,199,"供应商 B"],
["P003","产品 C","食品",200,150,49,"供应商 C"]
]低库存预警公式(在 Excel 中添加):
=IF(D2<E2, "需要补货", "充足")---
🔄 批量处理示例
示例 1:批量生成发票
准备数据 (invoices.json):
[
{
"invoice_no": "FP20260001",
"customer_name": "甲公司",
"items": "技术服务费",
"amount": "50000",
"tax_rate": "6%",
"date": "2026-02-22",
"filename": "发票_FP20260001.docx"
},
{
"invoice_no": "FP20260002",
"customer_name": "乙公司",
"items": "产品采购",
"amount": "120000",
"tax_rate": "13%",
"date": "2026-02-22",
"filename": "发票_FP20260002.docx"
}
]执行批量生成:
python scripts/batch_processor.py templates \
--folder ./invoices \
--template invoice_template.docx \
--data invoices.json---
示例 2:月度报告合并
文件夹结构:
./monthly_reports/
├── 2025-01_sales.xlsx
├── 2025-02_sales.xlsx
├── 2025-03_sales.xlsx
└── ...合并命令:
python scripts/excel_processor.py merge ./monthly_reports/ \
--output 2025_annual_sales.xlsx \
--sheet "全年汇总"添加月份标识(Python 脚本):
import pandas as pd
from openpyxl import Workbook
from pathlib import Path
folder = Path('./monthly_reports')
wb = Workbook()
ws = wb.active
ws.title = "全年汇总"
# 写入表头
ws.append(['月份', '日期', '产品', '销售额', '数量'])
# 遍历所有文件
for file in sorted(folder.glob('*.xlsx')):
month = file.stem # 例如:2025-01
df = pd.read_excel(file)
df.insert(0, '月份', month)
for _, row in df.iterrows():
ws.append(row.tolist())
wb.save('2025_annual_sales.xlsx')
print('✓ 合并完成')---
示例 3:Excel 批量转 CSV
场景:将 100 个 Excel 文件转换为 CSV 格式
python scripts/batch_processor.py convert \
--folder ./excel_files \
--from xlsx \
--to csv \
--output ./csv_files---
📈 数据分析示例
示例 1:销售趋势分析
import pandas as pd
import matplotlib.pyplot as plt
# 读取数据
df = pd.read_excel('sales_data.xlsx')
# 按日期汇总
daily_sales = df.groupby('日期')['销售额'].sum()
# 绘制趋势图
plt.figure(figsize=(12, 6))
daily_sales.plot(kind='line', marker='o')
plt.title('销售趋势图')
plt.xlabel('日期')
plt.ylabel('销售额')
plt.grid(True)
plt.savefig('sales_trend.png')
plt.show()---
示例 2:数据透视表
import pandas as pd
df = pd.read_excel('sales_data.xlsx')
# 按区域和产品透视
pivot = pd.pivot_table(
df,
values='销售额',
index='区域',
columns='产品',
aggfunc='sum',
margins=True, # 添加总计
margins_name='总计'
)
# 导出
pivot.to_excel('sales_pivot.xlsx')
print(pivot)---
示例 3:数据可视化
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_excel('sales_data.xlsx')
# 创建仪表板式图表
fig, axes = plt.subplots(2, 2, figsize=(14, 10))
# 1. 各区域销售额饼图
region_sales = df.groupby('区域')['销售额'].sum()
axes[0, 0].pie(region_sales, labels=region_sales.index, autopct='%1.1f%%')
axes[0, 0].set_title('区域销售占比')
# 2. 产品销售柱状图
product_sales = df.groupby('产品')['销售额'].sum()
axes[0, 1].bar(product_sales.index, product_sales.values)
axes[0, 1].set_title('产品销售对比')
axes[0, 1].tick_params(axis='x', rotation=45)
# 3. 销售趋势折线图
daily_sales = df.groupby('日期')['销售额'].sum()
axes[1, 0].plot(daily_sales.index, daily_sales.values, marker='o')
axes[1, 0].set_title('销售趋势')
axes[1, 0].tick_params(axis='x', rotation=45)
# 4. 数量 - 销售额散点图
axes[1, 1].scatter(df['数量'], df['销售额'], alpha=0.5)
axes[1, 1].set_title('数量 vs 销售额')
axes[1, 1].set_xlabel('数量')
axes[1, 1].set_ylabel('销售额')
plt.tight_layout()
plt.savefig('sales_dashboard.png', dpi=150)
print('✓ 仪表板已保存:sales_dashboard.png')---
🎯 综合案例
案例:自动化月度报告生成
目标:每月初自动生成上月销售报告(Word + Excel)
步骤:
1. 准备数据 - 从数据库/系统导出原始销售数据到 raw_sales.xlsx
2. 数据处理 - 使用 Excel 脚本整理数据:
python scripts/excel_processor.py analyze raw_sales.xlsx3. 生成统计表格 - 创建汇总 Excel:
import pandas as pd
df = pd.read_excel('raw_sales.xlsx')
# 创建汇总
summary = pd.DataFrame({
'指标': ['总销售额', '总订单数', '平均客单价'],
'数值': [df['销售额'].sum(), len(df), df['销售额'].mean()]
})
summary.to_excel('monthly_summary.xlsx', index=False)4. 填充 Word 报告模板:
python scripts/word_processor.py template monthly_report.docx \
--output monthly_report_filled.docx \
--data '{
"month": "2026 年 1 月",
"total_sales": "1500000",
"total_orders": "5000",
"avg_order": "300",
"top_product": "产品 A",
"growth_rate": "15%"
}'5. 附加 Excel 明细 - 将汇总 Excel 作为附件
---
📝 模板文件下载
所有示例模板文件位于:
examples/templates/- Word 模板examples/data/- JSON 数据文件examples/output/- 示例输出
---
💡 提示与技巧
1. 模板设计:保持模板简洁,变量使用有意义的名称 2. 数据验证:批量处理前先用少量数据测试 3. 备份:处理重要文件前先备份 4. 编码:JSON 文件使用 UTF-8 编码 5. 路径:使用绝对路径避免路径问题
[
{
"name": "张伟",
"position": "技术总监",
"event_name": "2026 科技创新峰会",
"event_date": "2026 年 3 月 15 日 14:00",
"event_location": "北京国际会议中心 三层宴会厅",
"rsvp_date": "2026 年 3 月 10 日",
"company_name": "科技创新有限公司",
"date": "2026 年 2 月 22 日",
"filename": "邀请函_张伟.docx"
},
{
"name": "李娜",
"position": "产品总监",
"event_name": "2026 科技创新峰会",
"event_date": "2026 年 3 月 15 日 14:00",
"event_location": "北京国际会议中心 三层宴会厅",
"rsvp_date": "2026 年 3 月 10 日",
"company_name": "科技创新有限公司",
"date": "2026 年 2 月 22 日",
"filename": "邀请函_李娜.docx"
},
{
"name": "王强",
"position": "市场总监",
"event_name": "2026 科技创新峰会",
"event_date": "2026 年 3 月 15 日 14:00",
"event_location": "北京国际会议中心 三层宴会厅",
"rsvp_date": "2026 年 3 月 10 日",
"company_name": "科技创新有限公司",
"date": "2026 年 2 月 22 日",
"filename": "邀请函_王强.docx"
}
]
[
{
"name": "张三",
"company": "科技有限公司",
"position": "总经理",
"date": "2026 年 2 月 22 日",
"filename": "邀请函_张三.docx"
},
{
"name": "李四",
"company": "创新集团",
"position": "技术总监",
"date": "2026 年 2 月 22 日",
"filename": "邀请函_李四.docx"
},
{
"name": "王五",
"company": "数据智能公司",
"position": "产品经理",
"date": "2026 年 2 月 22 日",
"filename": "邀请函_王五.docx"
}
]
会议邀请函
尊敬的 {{name}} {{position}}:
诚邀您参加 {{event_name}} 活动。
活动时间:{{event_date}}
活动地点:{{event_location}}
活动议程:
1. 签到入场
2. 主题演讲
3. 交流互动
4. 晚宴
请于 {{rsvp_date}} 前确认是否参加。
此致
敬礼
{{company_name}}
{{date}}
GitHub 上传指南
本指南帮助你将 Office Automation Skill 上传到 GitHub。
---
📋 前置准备
1. 创建 GitHub 账号
如果没有 GitHub 账号,访问 https://github.com 注册。
2. 配置 Git(首次使用)
# 设置你的 Git 用户名和邮箱
git config --global user.name "Your Name"
git config --global user.email "your.email@example.com"3. 设置 SSH 密钥(推荐)
# 生成 SSH 密钥
ssh-keygen -t ed25519 -C "your.email@example.com"
# 查看公钥
cat ~/.ssh/id_ed25519.pub
# 将公钥复制到 GitHub: Settings → SSH and GPG keys → New SSH key---
🚀 上传步骤
步骤 1:在 GitHub 创建仓库
1. 访问 https://github.com/new 2. 填写仓库信息:
- Repository name:
office-automation-skill(或你喜欢的名字) - Description:
Office Automation Skill for OpenClaw - Automate Word and Excel processing - Visibility: Public(公开)或 Private(私有)
- 不要勾选 "Add a README file"(我们已经有 README 了)
- 不要勾选 ".gitignore"(我们已经有 .gitignore 了)
- 不要勾选 "Choose a license"(我们已经有 LICENSE 了)
3. 点击 "Create repository"
步骤 2:添加远程仓库
创建仓库后,GitHub 会显示设置说明。执行以下命令:
cd /Users/bbaa/.openclaw/workspace/skills/office-automation
# 使用 HTTPS(需要每次输入密码/token)
git remote add origin https://github.com/YOUR_USERNAME/office-automation-skill.git
# 或使用 SSH(推荐,需要先配置 SSH 密钥)
git remote add origin git@github.com:YOUR_USERNAME/office-automation-skill.git注意:将 YOUR_USERNAME 替换为你的 GitHub 用户名。
步骤 3:推送到 GitHub
# 推送代码
git push -u origin main
# 如果是首次推送且使用 HTTPS,可能需要:
# - 使用 GitHub Personal Access Token 代替密码
# - 或在 GitHub 设置中启用密码登录步骤 4:验证上传
访问你的 GitHub 仓库页面,确认所有文件已上传:
- README.md
- SKILL.md
- scripts/
- docs/
- examples/
- references/
---
🔐 使用 Personal Access Token
GitHub 已不再支持使用账户密码进行 Git 操作。需要使用 Personal Access Token:
创建 Token
1. 访问 https://github.com/settings/tokens 2. 点击 "Generate new token (classic)" 3. 填写:
- Note:
office-automation-skill - Expiration: 选择过期时间(建议 90 天或更长)
- Scopes: 勾选
repo(完整仓库权限)
4. 点击 "Generate token" 5. 复制并保存 token(只显示一次!)
使用 Token
推送时使用 token 代替密码:
git push -u origin main
# Username: YOUR_USERNAME
# Password: 粘贴你的 token(不会显示)---
📦 发布到 ClawHub(可选)
如果你想让其他人通过 OpenClaw 安装这个技能:
1. 确保仓库是公开的
2. 提交到 ClawHub
访问 https://clawhub.com/submit 提交你的技能。
3. 用户安装
用户可以使用以下命令安装:
openclaw skills install github:YOUR_USERNAME/office-automation-skill---
🔄 后续更新
修改代码后推送
cd /Users/bbaa/.openclaw/workspace/skills/office-automation
# 查看变更
git status
# 添加变更
git add -A
# 提交
git commit -m "feat: 添加新功能 / fix: 修复问题 / docs: 更新文档"
# 推送
git push创建 Release
1. 访问 GitHub 仓库页面 2. 点击 "Releases" → "Create a new release" 3. 填写:
- Tag version:
v1.0.0 - Release title:
v1.0.0 - Initial Release - Description: 更新内容(可参考 CHANGELOG.md)
4. 点击 "Publish release"
---
🏷️ 添加主题标签
在 GitHub 仓库页面右侧,添加以下 topics:
openclawoffice-automationwordexcelpythonautomationskill
---
📊 仓库徽章
在 README 中使用徽章展示项目状态:
[](https://opensource.org/licenses/MIT)
[](https://www.python.org/downloads/)
[](https://github.com/YOUR_USERNAME/office-automation-skill/stargazers)---
❓ 常见问题
Q: 推送失败 "Permission denied"
A: 检查 SSH 密钥是否正确配置,或使用 HTTPS + Token。
Q: 如何修改远程仓库地址?
A:
git remote set-url origin https://github.com/NEW_USERNAME/NEW_REPO.gitQ: 如何删除已提交的文件?
A:
git rm filename.txt
git commit -m "remove: 删除文件"
git pushQ: 如何回滚到之前的版本?
A:
git log --oneline # 查看提交历史
git reset --hard COMMIT_ID # 回滚到指定提交
git push --force # 强制推送(小心使用!)---
📞 需要帮助?
- GitHub 文档:https://docs.github.com/
- Git 教程:https://git-scm.com/book/zh/v2
- OpenClaw 社区:https://discord.com/invite/clawd
---
祝你上传顺利! 🎉
MIT License
Copyright (c) 2026 OpenClaw Office Automation Skill
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
🚀 推送到 GitHub - 快速指南
当前状态
✅ Git 仓库已初始化 ✅ 代码已提交 (commit: 21b32f9) ✅ 远程仓库地址已设置:https://github.com/texiaoyao/office-automation-skill.git ⏳ 需要创建 GitHub 仓库并推送
---
📋 推送步骤
步骤 1:在 GitHub 创建仓库
1. 访问: https://github.com/new
2. 填写信息:
- Repository name:
office-automation-skill - Description:
Office Automation Skill for OpenClaw - Automate Word and Excel processing - Visibility: 🌍 Public (公开,让其他人可以使用)
- ❌ 不要勾选 "Add a README file"
- ❌ 不要勾选 ".gitignore"
- ❌ 不要勾选 "Choose a license"
3. 点击: "Create repository"
---
步骤 2:推送代码
创建仓库后,在终端执行:
cd /Users/bbaa/.openclaw/workspace/skills/office-automation
# 推送到 GitHub
git push -u origin main认证方式(二选一):
方式 A:使用 Personal Access Token(推荐)
1. 访问 https://github.com/settings/tokens 2. 点击 "Generate new token (classic)" 3. 填写:
- Note:
office-automation-skill - Expiration: 90 天或更长
- Scopes: 勾选 ✅
repo
4. 点击 "Generate token" 5. 复制 token(只显示一次!) 6. 推送时:
- Username:
texiaoyao - Password: 粘贴你的 token(不会显示字符)
方式 B:使用 GitHub CLI(如果已安装)
# 如果已安装 gh CLI
gh auth login
gh repo create texiaoyao/office-automation-skill --public --source=. --push---
步骤 3:验证
访问 https://github.com/texiaoyao/office-automation-skill 确认所有文件已上传。
---
🎯 快速命令
# 查看当前状态
cd /Users/bbaa/.openclaw/workspace/skills/office-automation
git status
# 查看提交历史
git log --oneline
# 推送
git push -u origin main
# 后续更新
git add -A
git commit -m "feat: 更新说明"
git push---
❓ 遇到问题?
"Repository not found"
→ 确保已在 GitHub 创建仓库
"Authentication failed"
→ 使用 Personal Access Token 代替密码
"Permission denied"
→ 检查仓库所有者是否为 texiaoyao
---
📞 需要帮助?
执行以下命令查看详细信息:
git remote -v
git log --oneline创建好仓库后,执行 `git push -u origin main` 即可! 🎉
📊 Office Automation Skill for OpenClaw
  
自动化处理 Word 和 Excel 文件的 OpenClaw 技能
Automate Word and Excel document processing with OpenClaw
---
🌟 功能特点 / Features
- 📄 Word 处理 - 读取、写入、模板填充、表格提取
- 📊 Excel 处理 - 读取、写入、合并、转换、数据分析
- 🔄 批量处理 - 批量生成文档、格式转换、数据提取
- 🤖 AI 集成 - 与 OpenClaw 无缝集成,支持自然语言命令
---
🚀 快速开始 / Quick Start
安装依赖 / Install Dependencies
pip install python-docx openpyxl pandas测试脚本 / Test Scripts
# Word 测试 / Word Test
python scripts/word_processor.py write test.docx --content "Hello World" --title "Test"
# Excel 测试 / Excel Test
python scripts/excel_processor.py write test.xlsx --data '[["Name","Age"],["Alice",25]]' --headers "Name,Age"---
📖 文档 / Documentation
| 文档 | 说明 |
|---|---|
| 使用指南 | 完整的使用教程和命令参考 |
| 示例集合 | 实战案例和代码示例 |
| API 参考 | Python API 详细文档 |
---
💡 使用示例 / Usage Examples
Word 模板填充
python scripts/word_processor.py template contract.docx \
--output contract_filled.docx \
--data '{"name":"张三","date":"2026-02-22"}'Excel 数据合并
python scripts/excel_processor.py merge ./reports/ --output all.xlsx批量生成文档
python scripts/batch_processor.py templates \
--folder ./output \
--template invitation.docx \
--data attendees.json---
📁 项目结构 / Project Structure
office-automation/
├── SKILL.md # OpenClaw 技能定义
├── README.md # 本文件
├── LICENSE # MIT 许可证
├── .gitignore # Git 忽略文件
├── scripts/
│ ├── word_processor.py # Word 处理脚本
│ ├── excel_processor.py # Excel 处理脚本
│ └── batch_processor.py # 批量处理脚本
├── references/
│ └── office_api.md # API 参考文档
├── docs/
│ ├── 使用指南.md # 使用教程
│ └── 示例集合.md # 示例代码
└── examples/
└── sample_data.json # 示例数据---
🔧 脚本命令 / Script Commands
word_processor.py
| 命令 | 说明 |
|---|---|
read <file> | 读取文档内容 |
write <output> --content "文本" | 创建新文档 |
template <文件> --output <输出> --data 'JSON' | 填充模板 |
extract <文件> --table 0 | 提取表格到 CSV |
excel_processor.py
| 命令 | 说明 |
|---|---|
read <file> --sheet Sheet1 | 读取 Excel |
write <output> --data 'JSON' | 写入数据 |
merge <文件夹> --output <输出> | 合并文件 |
convert <文件> --to csv/xlsx | 格式转换 |
analyze <文件> | 数据分析 |
batch_processor.py
| 命令 | 说明 |
|---|---|
templates --folder --template --data | 批量填充模板 |
convert --folder --from --to --output | 批量转换格式 |
extract --folder --output | 批量提取表格 |
---
🎯 实战案例 / Use Cases
1. 批量生成合同 / Batch Generate Contracts
python scripts/batch_processor.py templates \
--folder ./contracts \
--template contract_template.docx \
--data clients.json2. 月度报告合并 / Merge Monthly Reports
python scripts/excel_processor.py merge ./monthly_reports/ \
--output yearly_report.xlsx3. 数据提取与分析 / Extract and Analyze Data
# 提取 Word 表格
python scripts/word_processor.py extract report.docx
# 分析 Excel 数据
python scripts/excel_processor.py analyze sales.xlsx---
⚠️ 注意事项 / Notes
1. Word 格式 - 仅支持 .docx(不支持旧版 .doc) 2. Excel 格式 - 支持 .xlsx 和 .xlsm 3. 编码 - CSV 文件使用 UTF-8-BOM 编码 4. 大文件 - 超过 100MB 建议分批次处理
---
🤝 与 OpenClaw 集成 / OpenClaw Integration
在 OpenClaw 聊天中直接使用:
请帮我读取 document.docx 的内容
从 data.xlsx 提取销售数据
批量生成 100 份合同,数据在 data.json 中---
📄 许可证 / License
本项目采用 MIT 许可证 - 查看 LICENSE 文件了解详情。
---
🙏 致谢 / Acknowledgments
- OpenClaw - AI 代理网关框架
- python-docx - Word 处理库
- openpyxl - Excel 处理库
- pandas - 数据分析库
---
📮 联系方式 / Contact
- 🐛 问题反馈:GitHub Issues
- 💬 社区讨论:OpenClaw Discord
- 📚 更多技能:ClawHub
---
<div align="center">
Made with ❤️ for OpenClaw Community
</div>
Office API 参考
Python 库
python-docx (Word 处理)
安装:
pip install python-docx常用操作:
from docx import Document
from docx.shared import Inches, Pt
# 创建文档
doc = Document()
doc.add_heading('标题', 0)
doc.add_paragraph('正文内容')
doc.save('output.docx')
# 读取文档
doc = Document('input.docx')
for para in doc.paragraphs:
print(para.text)
# 添加表格
table = doc.add_table(rows=3, cols=3)
table.cell(0, 0).text = '单元格内容'
# 设置格式
paragraph = doc.add_paragraph()
run = paragraph.add_run('加粗文本')
run.bold = True
run.font.size = Pt(12)文档: https://python-docx.readthedocs.io/
---
openpyxl (Excel 处理)
安装:
pip install openpyxl常用操作:
from openpyxl import Workbook, load_workbook
# 创建工作簿
wb = Workbook()
ws = wb.active
ws['A1'] = '数据'
ws.append([1, 2, 3])
wb.save('output.xlsx')
# 读取工作簿
wb = load_workbook('input.xlsx', data_only=True)
ws = wb['Sheet1']
for row in ws.iter_rows(values_only=True):
print(row)
# 设置样式
from openpyxl.styles import Font, Alignment
ws['A1'].font = Font(bold=True)
ws['A1'].alignment = Alignment(horizontal='center')文档: https://openpyxl.readthedocs.io/
---
pandas (数据分析)
安装:
pip install pandas常用操作:
import pandas as pd
# 读取 Excel
df = pd.read_excel('data.xlsx', sheet_name='Sheet1')
# 数据筛选
filtered = df[df['column'] > 100]
# 数据统计
stats = df.describe()
# 数据透视
pivot = df.pivot_table(values='value', index='row', columns='col', aggfunc='sum')
# 导出
df.to_excel('output.xlsx', index=False)
df.to_csv('output.csv', index=False, encoding='utf-8-sig')文档: https://pandas.pydata.org/docs/
---
模板变量格式
Word 模板使用 {{变量名}} 格式:
合同编号:{{contract_number}}
甲方:{{party_a}}
乙方:{{party_b}}
日期:{{date}}JSON 数据格式:
[
{
"contract_number": "HT2026001",
"party_a": "甲公司",
"party_b": "乙公司",
"date": "2026-02-22",
"filename": "合同_001.docx"
}
]---
常见问题
Q: 支持 .doc 格式吗?
A: 不支持。python-docx 只支持 .docx 格式。旧版 .doc 需要先用 Word 另存为 .docx。
Q: Excel 宏 (.xlsm) 支持吗?
A: openpyxl 可以读取 .xlsm 文件,但不会保留宏代码。
Q: 如何处理大文件?
A: 使用 pandas 的 chunksize 参数分块读取,或直接用 openpyxl 的 iter_rows()。
Q: 中文乱码怎么办?
A: 确保使用 encoding='utf-8-sig' 保存 CSV 文件。
---
脚本命令速查
word_processor.py
# 读取
python word_processor.py read file.docx
# 写入
python word_processor.py write out.docx --content "内容" --title "标题"
# 模板填充
python word_processor.py template doc.docx --output out.docx --data '{"key": "value"}'
# 提取表格
python word_processor.py extract file.docx --table 0 --output-dir ./csvexcel_processor.py
# 读取
python excel_processor.py read data.xlsx --sheet Sheet1
# 写入
python excel_processor.py write out.xlsx --data '[["a","b"],["1","2"]]' --headers "col1,col2"
# 合并
python excel_processor.py merge ./files/ --output all.xlsx
# 转换
python excel_processor.py convert file.xlsx --to csv
# 分析
python excel_processor.py analyze sales.xlsx --pivotbatch_processor.py
# 批量填充模板
python batch_processor.py templates --folder ./output --template template.docx --data data.json
# 批量转换
python batch_processor.py convert --folder ./input --from xlsx --to csv --output ./output
# 批量提取表格
python batch_processor.py extract --folder ./docs --output ./tables#!/usr/bin/env python3
"""
批量处理脚本
支持批量处理 Word 和 Excel 文件
"""
import argparse
import json
import sys
from pathlib import Path
from datetime import datetime
try:
from docx import Document
import openpyxl
import pandas as pd
except ImportError:
print("错误:请安装必要的库")
print("运行:pip install python-docx openpyxl pandas")
sys.exit(1)
def batch_fill_templates(folder_path: str, template_path: str, data_file: str, output_folder: str):
"""批量填充 Word 模板"""
folder = Path(folder_path)
output = Path(output_folder)
output.mkdir(parents=True, exist_ok=True)
# 读取数据
with open(data_file, 'r', encoding='utf-8') as f:
data_list = json.load(f)
template = Document(template_path)
for i, data in enumerate(data_list):
# 复制模板
doc = Document(template_path)
# 替换段落
for para in doc.paragraphs:
for key, value in data.items():
if f"{{{{{key}}}}}" in para.text:
para.text = para.text.replace(f"{{{{{key}}}}}", str(value))
# 替换表格
for table in doc.tables:
for row in table.rows:
for cell in row.cells:
for key, value in data.items():
if f"{{{{{key}}}}}" in cell.text:
cell.text = cell.text.replace(f"{{{{{key}}}}}", str(value))
# 保存
output_name = data.get('filename', f"document_{i+1}.docx")
output_path = output / output_name
doc.save(output_path)
print(f"✓ 已生成:{output_path}")
print(f"\n✓ 批量处理完成:共生成 {len(data_list)} 个文件")
def batch_convert_folder(folder_path: str, from_format: str, to_format: str, output_folder: str):
"""批量转换文件格式"""
folder = Path(folder_path)
output = Path(output_folder)
output.mkdir(parents=True, exist_ok=True)
if from_format == "xlsx" and to_format == "csv":
files = list(folder.glob("*.xlsx"))
for file in files:
df = pd.read_excel(file)
csv_path = output / f"{file.stem}.csv"
df.to_csv(csv_path, index=False, encoding='utf-8-sig')
print(f"✓ 已转换:{file.name} → {csv_path.name}")
elif from_format == "csv" and to_format == "xlsx":
files = list(folder.glob("*.csv"))
for file in files:
df = pd.read_csv(file, encoding='utf-8')
xlsx_path = output / f"{file.stem}.xlsx"
df.to_excel(xlsx_path, index=False)
print(f"✓ 已转换:{file.name} → {xlsx_path.name}")
else:
print(f"错误:不支持的转换 {from_format} → {to_format}")
return
print(f"\n✓ 批量转换完成:共处理 {len(files)} 个文件")
def batch_extract_tables(folder_path: str, output_folder: str):
"""批量提取 Word 文档中的表格"""
folder = Path(folder_path)
output = Path(output_folder)
output.mkdir(parents=True, exist_ok=True)
docx_files = list(folder.glob("*.docx"))
for file in docx_files:
doc = Document(file)
base_name = file.stem
for i, table in enumerate(doc.tables):
csv_path = output / f"{base_name}_table_{i}.csv"
with open(csv_path, 'w', encoding='utf-8') as f:
for row in table.rows:
line = ','.join(f'"{cell.text}"' for cell in row.cells)
f.write(line + '\n')
print(f"✓ 已提取:{file.name} → {csv_path.name}")
print(f"\n✓ 批量提取完成:共处理 {len(docx_files)} 个文档")
def main():
parser = argparse.ArgumentParser(description="批量处理工具")
subparsers = parser.add_subparsers(dest="command", help="命令")
# templates 命令
tpl_parser = subparsers.add_parser("templates", help="批量填充模板")
tpl_parser.add_argument("--folder", required=True, help="输出文件夹")
tpl_parser.add_argument("--template", required=True, help="模板文件路径")
tpl_parser.add_argument("--data", required=True, help="JSON 数据文件路径")
# convert 命令
conv_parser = subparsers.add_parser("convert", help="批量转换格式")
conv_parser.add_argument("--folder", required=True, help="输入文件夹")
conv_parser.add_argument("--from", dest="from_fmt", required=True, choices=["xlsx", "csv"])
conv_parser.add_argument("--to", dest="to_fmt", required=True, choices=["xlsx", "csv"])
conv_parser.add_argument("--output", required=True, help="输出文件夹")
# extract 命令
ext_parser = subparsers.add_parser("extract", help="批量提取表格")
ext_parser.add_argument("--folder", required=True, help="包含 Word 文档的文件夹")
ext_parser.add_argument("--output", required=True, help="输出文件夹")
args = parser.parse_args()
if args.command == "templates":
batch_fill_templates(args.folder, args.template, args.data, args.output)
elif args.command == "convert":
batch_convert_folder(args.folder, args.from_fmt, args.to_fmt, args.output)
elif args.command == "extract":
batch_extract_tables(args.folder, args.output)
else:
parser.print_help()
if __name__ == "__main__":
main()
#!/usr/bin/env python3
"""
Excel 表格处理脚本
支持读取、写入、合并、转换、数据分析等功能
"""
import argparse
import json
import sys
from pathlib import Path
from datetime import datetime
try:
import openpyxl
from openpyxl import Workbook, load_workbook
from openpyxl.utils.dataframe import dataframe_to_rows
import pandas as pd
except ImportError:
print("错误:请安装 openpyxl 和 pandas 库")
print("运行:pip install openpyxl pandas")
sys.exit(1)
def read_excel(file_path: str, sheet_name: str = None) -> dict:
"""读取 Excel 文件内容"""
wb = load_workbook(file_path, data_only=True)
result = {
"file": file_path,
"sheets": {},
"sheet_names": wb.sheetnames
}
sheets_to_read = [sheet_name] if sheet_name else wb.sheetnames
for sheet_name in sheets_to_read:
if sheet_name not in wb.sheetnames:
print(f"警告:工作表 '{sheet_name}' 不存在")
continue
ws = wb[sheet_name]
data = []
for row in ws.iter_rows(values_only=True):
data.append(list(row))
result["sheets"][sheet_name] = {
"rows": len(data),
"cols": len(data[0]) if data else 0,
"data": data
}
return result
def write_excel(file_path: str, data: list, sheet_name: str = "Sheet1", headers: list = None):
"""写入数据到 Excel 文件"""
wb = Workbook()
ws = wb.active
ws.title = sheet_name
# 写入表头
if headers:
ws.append(headers)
# 写入数据
for row in data:
ws.append(row)
# 自动调整列宽
for column in ws.columns:
max_length = 0
column_letter = column[0].column_letter
for cell in column:
try:
if len(str(cell.value)) > max_length:
max_length = len(str(cell.value))
except:
pass
adjusted_width = min(max_length + 2, 50)
ws.column_dimensions[column_letter].width = adjusted_width
wb.save(file_path)
print(f"✓ Excel 文件已保存:{file_path}")
def merge_excel_files(folder_path: str, output_path: str, sheet_name: str = "Merged"):
"""合并文件夹中的所有 Excel 文件"""
folder = Path(folder_path)
excel_files = list(folder.glob("*.xlsx")) + list(folder.glob("*.xlsm"))
if not excel_files:
print(f"错误:在 {folder_path} 中未找到 Excel 文件")
return
all_data = []
headers = None
for file in excel_files:
try:
df = pd.read_excel(file)
if headers is None:
headers = df.columns.tolist()
all_data.extend(df.values.tolist())
print(f"✓ 已读取:{file.name}")
except Exception as e:
print(f"⚠ 跳过文件 {file.name}: {e}")
if all_data:
write_excel(output_path, all_data, sheet_name, headers)
print(f"✓ 已合并 {len(excel_files)} 个文件,共 {len(all_data)} 行数据")
else:
print("错误:没有可合并的数据")
def convert_excel(file_path: str, to_format: str = "csv", output_path: str = None):
"""转换 Excel 文件格式"""
if output_path is None:
output_path = Path(file_path).with_suffix(f".{to_format}")
if to_format.lower() == "csv":
# Excel 转 CSV
excel_file = pd.ExcelFile(file_path)
for sheet_name in excel_file.sheet_names:
df = pd.read_excel(file_path, sheet_name=sheet_name)
csv_path = Path(output_path).parent / f"{Path(output_path).stem}_{sheet_name}.csv"
df.to_csv(csv_path, index=False, encoding='utf-8-sig')
print(f"✓ 已导出:{csv_path}")
elif to_format.lower() == "xlsx":
# CSV 转 Excel
df = pd.read_csv(file_path, encoding='utf-8')
df.to_excel(output_path, index=False)
print(f"✓ 已转换:{output_path}")
else:
print(f"错误:不支持的格式 '{to_format}'")
def analyze_excel(file_path: str, sheet_name: str = None, pivot: bool = False):
"""分析 Excel 数据"""
df = pd.read_excel(file_path, sheet_name=sheet_name)
print(f"\n📊 数据分析报告:{Path(file_path).name}")
print("=" * 50)
print(f"行数:{len(df)}")
print(f"列数:{len(df.columns)}")
print(f"\n列名:{list(df.columns)}")
print(f"\n数据类型:")
for col, dtype in df.dtypes.items():
print(f" {col}: {dtype}")
print(f"\n缺失值统计:")
missing = df.isnull().sum()
for col, count in missing.items():
if count > 0:
print(f" {col}: {count} ({count/len(df)*100:.1f}%)")
if not missing.any():
print(" 无缺失值 ✓")
print(f"\n数值列统计:")
numeric_cols = df.select_dtypes(include=['number']).columns
if len(numeric_cols) > 0:
print(df[numeric_cols].describe().to_string())
else:
print(" 无数值列")
if pivot:
print(f"\n⚠️ 透视表需要提供行列参数,使用 --pivot-rows 和 --pivot-cols 指定")
def main():
parser = argparse.ArgumentParser(description="Excel 表格处理工具")
subparsers = parser.add_subparsers(dest="command", help="命令")
# read 命令
read_parser = subparsers.add_parser("read", help="读取 Excel 内容")
read_parser.add_argument("file", help="Excel 文件路径")
read_parser.add_argument("--sheet", help="工作表名称(不指定则读取全部)")
# write 命令
write_parser = subparsers.add_parser("write", help="创建 Excel 文件")
write_parser.add_argument("output", help="输出文件路径")
write_parser.add_argument("--data", required=True, help="JSON 格式数据")
write_parser.add_argument("--sheet", default="Sheet1", help="工作表名称")
write_parser.add_argument("--headers", help="表头(逗号分隔)")
# merge 命令
merge_parser = subparsers.add_parser("merge", help="合并 Excel 文件")
merge_parser.add_argument("folder", help="包含 Excel 文件的文件夹")
merge_parser.add_argument("--output", required=True, help="输出文件路径")
merge_parser.add_argument("--sheet", default="Merged", help="工作表名称")
# convert 命令
convert_parser = subparsers.add_parser("convert", help="转换文件格式")
convert_parser.add_argument("file", help="输入文件路径")
convert_parser.add_argument("--to", required=True, choices=["csv", "xlsx"], help="目标格式")
convert_parser.add_argument("--output", help="输出文件路径")
# analyze 命令
analyze_parser = subparsers.add_parser("analyze", help="数据分析")
analyze_parser.add_argument("file", help="Excel 文件路径")
analyze_parser.add_argument("--sheet", help="工作表名称")
analyze_parser.add_argument("--pivot", action="store_true", help="生成透视表")
args = parser.parse_args()
if args.command == "read":
result = read_excel(args.file, args.sheet)
print(json.dumps(result, ensure_ascii=False, indent=2))
elif args.command == "write":
data = json.loads(args.data)
headers = args.headers.split(',') if args.headers else None
write_excel(args.output, data, args.sheet, headers)
elif args.command == "merge":
merge_excel_files(args.folder, args.output, args.sheet)
elif args.command == "convert":
convert_excel(args.file, args.to, args.output)
elif args.command == "analyze":
analyze_excel(args.file, args.sheet, args.pivot)
else:
parser.print_help()
if __name__ == "__main__":
main()
#!/usr/bin/env python3
"""
Word 文档处理脚本
支持读取、写入、模板填充、表格提取等功能
"""
import argparse
import json
import sys
from pathlib import Path
try:
from docx import Document
from docx.shared import Inches, Pt, RGBColor
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.enum.style import WD_STYLE_TYPE
except ImportError:
print("错误:请安装 python-docx 库")
print("运行:pip install python-docx")
sys.exit(1)
def read_document(file_path: str) -> dict:
"""读取 Word 文档内容"""
doc = Document(file_path)
content = {
"paragraphs": [],
"tables": [],
"sections": len(doc.sections)
}
# 读取段落
for i, para in enumerate(doc.paragraphs):
content["paragraphs"].append({
"index": i,
"text": para.text,
"style": para.style.name if para.style else None
})
# 读取表格
for i, table in enumerate(doc.tables):
table_data = []
for row in table.rows:
row_data = [cell.text for cell in row.cells]
table_data.append(row_data)
content["tables"].append({
"index": i,
"rows": len(table.rows),
"cols": len(table.columns),
"data": table_data
})
return content
def write_document(file_path: str, content: str, title: str = None):
"""创建新的 Word 文档"""
doc = Document()
if title:
doc.add_heading(title, 0)
# 添加段落
for paragraph in content.split('\n'):
if paragraph.strip():
doc.add_paragraph(paragraph)
doc.save(file_path)
print(f"✓ 文档已保存:{file_path}")
def fill_template(template_path: str, output_path: str, data: dict):
"""填充 Word 模板(替换 {{变量}} 格式)"""
doc = Document(template_path)
# 替换段落中的变量
for para in doc.paragraphs:
for key, value in data.items():
if f"{{{{{key}}}}}" in para.text:
para.text = para.text.replace(f"{{{{{key}}}}}", str(value))
# 替换表格中的变量
for table in doc.tables:
for row in table.rows:
for cell in row.cells:
for key, value in data.items():
if f"{{{{{key}}}}}" in cell.text:
cell.text = cell.text.replace(f"{{{{{key}}}}}", str(value))
doc.save(output_path)
print(f"✓ 模板已填充并保存:{output_path}")
def extract_tables(file_path: str, table_index: int = None, output_dir: str = "."):
"""提取 Word 文档中的表格到 CSV"""
doc = Document(file_path)
base_name = Path(file_path).stem
tables_to_extract = []
if table_index is not None:
if table_index < len(doc.tables):
tables_to_extract = [(table_index, doc.tables[table_index])]
else:
print(f"错误:表格索引 {table_index} 超出范围 (共 {len(doc.tables)} 个表格)")
return
else:
tables_to_extract = list(enumerate(doc.tables))
for idx, table in tables_to_extract:
csv_path = Path(output_dir) / f"{base_name}_table_{idx}.csv"
with open(csv_path, 'w', encoding='utf-8') as f:
for row in table.rows:
line = ','.join(f'"{cell.text}"' for cell in row.cells)
f.write(line + '\n')
print(f"✓ 表格 {idx} 已导出:{csv_path}")
def main():
parser = argparse.ArgumentParser(description="Word 文档处理工具")
subparsers = parser.add_subparsers(dest="command", help="命令")
# read 命令
read_parser = subparsers.add_parser("read", help="读取文档内容")
read_parser.add_argument("file", help="Word 文件路径")
# write 命令
write_parser = subparsers.add_parser("write", help="创建新文档")
write_parser.add_argument("output", help="输出文件路径")
write_parser.add_argument("--content", required=True, help="文档内容")
write_parser.add_argument("--title", help="文档标题")
# template 命令
template_parser = subparsers.add_parser("template", help="填充模板")
template_parser.add_argument("template", help="模板文件路径")
template_parser.add_argument("--output", required=True, help="输出文件路径")
template_parser.add_argument("--data", required=True, help="JSON 格式数据")
# extract 命令
extract_parser = subparsers.add_parser("extract", help="提取表格")
extract_parser.add_argument("file", help="Word 文件路径")
extract_parser.add_argument("--table", type=int, help="表格索引(不指定则提取全部)")
extract_parser.add_argument("--output-dir", default=".", help="输出目录")
args = parser.parse_args()
if args.command == "read":
result = read_document(args.file)
print(json.dumps(result, ensure_ascii=False, indent=2))
elif args.command == "write":
write_document(args.output, args.content, args.title)
elif args.command == "template":
data = json.loads(args.data)
fill_template(args.template, args.output, data)
elif args.command == "extract":
extract_tables(args.file, args.table, args.output_dir)
else:
parser.print_help()
if __name__ == "__main__":
main()
Related skills
How it compares
Choose office-automation over generic Python skills when you need opinionated Word and Excel scripting patterns with declared docx/xlsx dependencies.
FAQ
Which file formats does office-automation support?
Word .docx only and Excel .xlsx or .xlsm with UTF-8 encoding by default.
How do I fill a Word template?
Run word_processor.py template with --data JSON to replace template variables in the document.
What Python packages are required?
python-docx, openpyxl, and pandas installed with pip alongside python3 on PATH.
Is Office Automation safe to install?
skills.sh reports 3 of 3 security scanners passed. Review the Security Audits panel on this page before installing in production.