解析 skill-creator:如何编写高质量的 AI Skill

解析 skill-creator:如何编写高质量的 AI Skill

本文通过深入分析 Anthropic 官方 skill-creator 代码仓库,提炼出一套编写高质量 Agent Skill 的完整方法论。这些原则适用于 OpenCode、Claude Code、Cursor 等所有支持 Agent Skills 开放标准的 AI 工具。

一.从 skill-creator 仓库我们能学到什么?

1.1 skill-creator 是什么?

skill-creator 是 Anthropic 官方维护的一个 Skill,它的唯一目的就是教 AI 如何创建有效的 Skill。通过分析这个"教 AI 教 AI"的元 Skill,我们可以获得第一手的最佳实践。

仓库地址:github.com/anthropics/skills/tree/main/skills/skill-creator

1.2 核心文件结构分析

skill-creator/ ├── SKILL.md # 核心指南 ├── references/ # 参考文档 │ ├── output-patterns.md # 输出模式 │ └── workflows.md # 工作流模式 └── scripts/ # 辅助脚本 ├── init_skill.py # Skill 初始化脚本 ├── package_skill.py # 打包验证脚本 └── quick_validate.py # 快速验证脚本 

skill-creator 自身的 SKILL.md 只有 357 行,却涵盖了完整的 Skill 创建方法论。这说明简洁是 Skill 设计的第一原则

二、SKILL.md 的核心结构解析

通过分析 skill-creator/SKILL.md 的源码,我们发现一个高质量的 SKILL.md 包含以下部分:

2.1 YAML Frontmatter(元数据头)

---name: skill-creator description:| Guide for creating effective skills. This skill should be used when users want to create a new skill (or update an existing skill) that extends agent capabilities with specialized knowledge, workflows, or tool integrations.license: Complete terms in LICENSE.txt ---
  • namedescription 是唯一必需的字段
  • description 必须同时说明"技能做什么"和"何时使用它"
  • 所有"何时使用"的信息必须放在 description 中,因为 body 只在 Skill 触发后才加载

2.2 Body 正文结构

skill-creator 的 SKILL.md 采用以下结构:

正文使用祈使形式(imperative form),直接给出指令而非建议。例如:

“Challenge each piece of information” 质疑每一条信息

“Prefer concise examples over verbose explanations” 用简洁的例子替代冗长的解释

三、从源码提炼的 7 大核心原则

原则 1:上下文窗口是公共资源(Concise is Key)

源码原文:

“The context window is a public good. Skills share the context window with everything else the agent needs: system prompt, conversation history, other Skills’ metadata, and the actual user request.”

解读:

  • Skill 与系统提示、对话历史、其他 Skill 元数据、用户请求共享上下文窗口
  • 每个词都要有价值,不断质疑:“AI 真的需要这个解释吗?”
  • 默认假设 AI 已经很智能,只添加它不知道的信息

实践建议:

  • 用简洁示例替代冗长解释
  • SKILL.md 正文保持在 500 行以内
  • 接近限制时将内容拆分到 references/

原则 2:设置适当的自由度(Degrees of Freedom)

源码原文:

“Match the level of specificity to the task’s fragility and variability”

解读: 根据任务的脆弱性和可变性,匹配合适的约束级别:

自由度级别适用场景实现方式
高自由度多种方法有效、依赖上下文决策文本指令
中自由度有推荐模式、可接受变化伪代码或带参数的脚本
低自由度操作脆弱易错、一致性关键特定脚本、最少参数

原则 3:渐进式披露设计(Progressive Disclosure)

源码原文:

“Skills use a three-level loading system to manage context efficiently”

三级加载系统:

┌─────────────────────────────────────────────────────────┐ │ Level 1: 元数据 (name + description) │ │ 始终加载 (~100 tokens) │ ├─────────────────────────────────────────────────────────┤ │ Level 2: SKILL.md 正文 │ │ Skill 触发时加载 (< 5000 tokens 推荐) │ ├─────────────────────────────────────────────────────────┤ │ Level 3: 捆绑资源 │ │ 按需加载(无限制,脚本可不加载到上下文执行) │ └─────────────────────────────────────────────────────────┘ 

关键准则:

  • 保持 SKILL.md body 在 500 行以内
  • 拆分时必须从 SKILL.md 清晰引用其他文件
  • 说明何时读取这些文件

原则 4:不要在 Skill 中包含辅助文档

源码原文(What to Not Include in a Skill):

“A skill should only contain essential files that directly support its functionality. Do NOT create extraneous documentation or auxiliary files, including: README.md, INSTALLATION_GUIDE.md, QUICK_REFERENCE.md, CHANGELOG.md, etc.”

解读:

  • Skill 只应包含 AI Agent 完成工作所需的信息
  • 不应包含创建过程的辅助上下文、设置和测试程序、面向用户的文档
  • 额外的文档只会增加混乱

原则 5:编写高质量的 description

源码原文:

“Only name and description are read by the agent to determine when the skill triggers, so be clear and comprehensive about what the skill is and when it should be used.”

好的 description 示例(来自 docx Skill):

description: | Comprehensive document creation, editing, and analysis with support for tracked changes, comments, formatting preservation, and text extraction. Use when the agent needs to work with professional documents (.docx files) for: (1) Creating new documents, (2) Modifying or editing content, (3) Working with tracked changes, (4) Adding comments, or any other document tasks 

差的 description 示例:

description:"Helps with PDFs"

要点:

  • 同时包含"功能描述"和"触发场景"
  • 所有"何时使用"信息都放在 description 中
  • Body 只在触发后加载,所以 body 中的"何时使用"对 AI 没有帮助

原则 6:使用祈使/不定式形式

源码原文(Writing Guidelines):

“Always use imperative/infinitive form” (始终使用祈使句/动词原形形式)

推荐写法:

  • “Run the script to check dependencies” (运行该脚本以检查依赖项)
  • “Extract text using pandoc” (使用 pandoc 提取文本)
  • “Validate page count before merging PDFs” (在合并 PDF 文件之前先验证页数数量)

避免写法:

  • “You should run the script to check dependencies” (您应该运行该脚本以检查依赖项)
  • “We can use pandoc to extract text” (我们可以使用 pandoc 来提取文本)
  • “I recommend validating the page count” (我建议确认页面数量)

原则 7:避免信息重复

源码原文(Avoid duplication):

“Information should live in either SKILL.md or references files, not both. Prefer references files for detailed information unless it’s truly core to the skill—this keeps SKILL.md lean while making information discoverable without hogging the context window.”

信息应当要么存放在“SKILL.md”文件中,要么存放在参考资料文件中,不能同时存在这两种形式。除非这些信息对于skill而言是极其核心的,否则建议使用参考资料文件来存放详细信息——这样既能保持“SKILL.md”文件的简洁性,又能使信息易于查找,同时也不会占用过多的上下文信息窗口。

解读:

  • 信息只应存在于一处
  • 详细信息优先放在 references/
  • SKILL.md 只保留核心程序指令和工作流指导

四、Skill 创建的 6 步流程(源自源码)

skill-creator 的 SKILL.md 明确给出了创建 Skill 的 6 个步骤:

步骤 1:通过具体示例理解 Skill

源码原文:

“To create an effective skill, clearly understand concrete examples of how the skill will be used.”

要培养一项有效的技能,必须清楚地了解该技能具体如何被运用的实例。

实践方法:

  • 询问:“这个 Skill 应该支持什么功能?”
  • 询问:“你能给出一些使用示例吗?”
  • 询问:“用户会说什么来触发这个 Skill?”

示例: 构建 image-editor Skill 时:

  • “移除这张图片的红眼”
  • “将图片旋转 90 度”
  • “调整图片亮度”

步骤 2:规划可复用的 Skill 内容

源码原文:

“To turn concrete examples into an effective skill, analyze each example by: Considering how to execute on the example from scratch; Identifying what scripts, references, and assets would be helpful”

要将具体的实例转化为有效的技能,需对每个实例进行分析:思考如何从零开始执行该实例;确定哪些脚本、参考资料和资源会有所帮助。
Skill 类型示例查询可复用资源
pdf-editor“帮我旋转这个 PDF”scripts/rotate_pdf.py
webapp-builder“构建一个待办应用”assets/hello-world/模板
big-query“今天有多少用户登录?”references/schema.md

步骤 3:初始化 Skill

源码原文:

“When creating a new skill from scratch, always run the init_skill.py script.”

在从零开始创建新技能时,务必运行 init_skill.py 脚本
python scripts/init_skill.py <skill-name> --path <output-directory>

脚本功能:

  • 创建 Skill 目录
  • 生成带 frontmatter 和 TODO 的 SKILL.md 模板
  • 创建示例资源目录(scripts/、references/、assets/)

步骤 4:编辑 Skill

源码原文:

“When editing the (newly-generated or existing) skill, remember that the skill is being created for another instance of the agent to use.”

在编辑(新生成的或现有的)技能时,请记住,该技能是为该智能体的另一个实例而设计使用的。

关键要点:

  • 包含对另一个 AI 实例有益且非明显的信息
  • 考虑什么程序知识、领域细节或可复用资源能帮助另一个 AI 实例更有效地执行这些任务

学习经过验证的设计模式:

  • 多步骤流程:参见 references/workflows.md
  • 特定输出格式:参见 references/output-patterns.md

脚本测试要求:

“Added scripts must be tested by actually running them to ensure there are no bugs and that the output matches what is expected.”

新增的脚本必须通过实际运行来测试,以确保没有错误并且输出结果符合预期。

步骤 5:打包 Skill

源码原文:

“Once development of the skill is complete, it must be packaged into a distributable .skill file”

一旦该技能的开发工作完成,就必须将其打包成一个可分发的“.skill”文件。
python scripts/package_skill.py <path/to/skill-folder>[output-dir]

打包脚本功能:

  • 验证 YAML frontmatter 格式和必需字段
  • 验证 Skill 命名约定和目录结构
  • 验证 描述完整性和质量
  • 创建.skill 文件(zip 格式,.skill 扩展名)

步骤 6:迭代优化

源码原文:

“After testing the skill, users may request improvements. Often this happens right after using the skill, with fresh context of how the skill performed.”

在测试该技能后,用户可能会要求对其进行改进。这种情况通常会在使用该技能后立即发生,此时会有关于该技能表现的新情况描述。

迭代流程:

  1. 在真实任务中使用 Skill
  2. 注意困难或低效的地方
  3. 识别 SKILL.md 或资源的更新点
  4. 实现更改并再次测试

五、Agent Skills 开放标准

5.1 什么是 Agent Skills?

Agent Skills 是一个开放标准(agentskills.io),最初由 Anthropic 开发,现已被多个 AI 工具采纳:OpenCode,Claude Code,Cursor ,GitHub Copilot ,Ampcode ,trae

5.2 标准规范要点

目录结构:

skill-name/ └── SKILL.md # 必需 

可选目录:

  • scripts/ - 可执行代码
  • references/ - 参考文档
  • assets/ - 静态资源

SKILL.md 格式:

---name: skill-name # 必需,1-64 字符description: What this skill does # 必需,1-1024 字符license: Apache-2.0# 可选compatibility: Requirements # 可选,1-500 字符metadata:# 可选author: example-org version:"1.0"---# Markdown body with instructions

5.3 OpenCode 中的 Skill 存放位置

项目级 Skill:

.opencode/skills/<name>/SKILL.md # OpenCode 格式 .claude/skills/<name>/SKILL.md # Claude 兼容格式 .agents/skills/<name>/SKILL.md # Agents 兼容格式 

全局 Skill:

~/.config/opencode/skills/<name>/SKILL.md # OpenCode 全局 ~/.claude/skills/<name>/SKILL.md # Claude 兼容全局 ~/.agents/skills/<name>/SKILL.md # Agents 兼容全局 

六.完整示例:文档处理 Skill

基于 skill-creator 的方法论,创建一个 docx-processor Skill:

6.1 目录结构

docx-processor/ ├── SKILL.md # Skill 定义文件(核心) ├── README.md # 使用说明 ├── scripts/ # 可执行脚本 │ ├── extract_text.py # 文本提取 │ ├── add_toc.py # 添加目录 │ └── convert_format.py # 格式转换 ├── references/ # 参考文档 │ ├── ooxml-reference.md # OOXML 技术参考 │ └── formatting-guide.md # 格式化指南 └── assets/ # 静态资源 └── letterhead-template.docx # 信纸模板 

6.2 SKILL.md

--- name: docx-processor description: | 全面的 Word 文档 (.docx) 处理能力,包括文本提取、目录生成、 格式转换、页眉页脚设置。当用户需要处理 Word 文档、创建专业 报告、转换文档格式或提取文档内容时使用。 触发场景: - 提及 "Word 文档"、".docx"、"docx" - 请求创建报告、备忘录、信函 - 需要目录、页码、页眉页脚 - 提取或重组文档内容 license: MIT metadata: author: your-name version: "1.0" --- # DOCX 处理器## 快速参考| 任务 | 方法 ||-----|------|| 提取文本 |`python scripts/extract_text.py document.docx`|| 添加目录 |`python scripts/add_toc.py document.docx`|| 格式转换 |`python scripts/convert_format.py input.docx output.pdf`|## 详细指南### 提取文档内容 使用脚本提取纯文本: python scripts/extract_text.py document.docx 输出将保存为 `document.txt`。 ### 添加目录 运行脚本自动添加目录: python scripts/add_toc.py document.docx 脚本执行步骤: 1. 扫描文档中的标题 2. 生成目录结构 3. 插入到文档开头 输出文件:`document-with-toc.docx`### 格式转换 将 Word 文档转换为 PDF: python scripts/convert_format.py input.docx output.pdf 支持格式:docx → pdf, txt, html ### 使用信纸模板 创建带公司信头的新文档: from docx import Document # 加载模板 doc = Document('assets/letterhead-template.docx')# 添加内容 doc.add_paragraph('正文内容...')# 保存 doc.save('output.docx')## 高级功能 - **修订跟踪**:参见 [references/formatting-guide.md](references/formatting-guide.md) - **OOXML 细节**:参见 [references/ooxml-reference.md](references/ooxml-reference.md)

6.3 scripts/add_toc.py

#!/usr/bin/env python3""" 为 Word 文档添加目录 用法: python add_toc.py <document.docx> 输出: 生成带目录的新文档:<原文件名>-with-toc.docx """import sys from docx import Document from docx.shared import Pt defcollect_headings(doc: Document)->list:"""收集文档中的所有标题""" headings =[]for para in doc.paragraphs: style_name = para.style.name if style_name.startswith('Heading'):try: level =int(style_name.replace('Heading ','')) headings.append((level, para.text.strip()))except ValueError:continuereturn headings defadd_table_of_contents(docx_path:str)->str:"""为 Word 文档添加目录""" doc = Document(docx_path)# 收集所有标题 headings = collect_headings(doc)ifnot headings:print('警告:文档中没有找到标题样式(Heading 1-9)')print('提示:请使用 Word 的标题样式设置章节标题')returnNone# 在文档开头插入目录标题 first_para = doc.paragraphs[0] toc_title = first_para.insert_paragraph_before('目录') toc_title.style ='Heading 1'# 插入目录项 prev_para = toc_title for level, text in headings: indent =' '*(level -1)# 根据标题级别缩进 toc_item_text =f'{indent}{text}' toc_item = prev_para.insert_paragraph_before(toc_item_text) prev_para = toc_item # 在目录后添加空行 prev_para.insert_paragraph_before('')# 生成输出文件名 output_path = docx_path.replace('.docx','-with-toc.docx')# 保存文档 doc.save(output_path)return output_path defmain():iflen(sys.argv)!=2:print('用法:python add_toc.py <document.docx>')print('示例:python add_toc.py report.docx') sys.exit(1) docx_path = sys.argv[1]try: output_path = add_table_of_contents(docx_path)if output_path:print(f'目录已添加:{output_path}')else: sys.exit(1)except FileNotFoundError:print(f'错误:找不到文件 {docx_path}') sys.exit(1)except Exception as e:print(f'错误:{e}') sys.exit(1)if __name__ =='__main__': main()

6.4 scripts/convert_format.py

#!/usr/bin/env python3""" 转换 Word 文档格式 用法: python convert_format.py <input.docx> <output.pdf|txt|html> 支持的输出格式: - pdf:PDF 文档 - txt:纯文本 - html:网页格式 """import sys import subprocess import os defconvert_to_pdf(input_path:str, output_path:str)->bool:"""使用 LibreOffice 转换为 PDF"""try:# 使用 soffice 进行转换 cmd =['soffice','--headless','--convert-to','pdf','--outdir', os.path.dirname(os.path.abspath(output_path))or'.', input_path ] result = subprocess.run(cmd, capture_output=True, text=True)if result.returncode !=0:print(f'转换失败:{result.stderr}')returnFalse# LibreOffice 生成的文件名可能与预期不同 generated_pdf = input_path.replace('.docx','.pdf')if generated_pdf != output_path and os.path.exists(generated_pdf): os.rename(generated_pdf, output_path)returnTrueexcept FileNotFoundError:print('错误:未找到 LibreOffice (soffice)')print('请安装 LibreOffice:')print(' macOS: brew install --cask libreoffice')print(' Ubuntu: sudo apt-get install libreoffice')returnFalsedefconvert_to_txt(input_path:str, output_path:str)->bool:"""使用 pandoc 转换为纯文本"""try: cmd =['pandoc', input_path,'-o', output_path] result = subprocess.run(cmd, capture_output=True, text=True)if result.returncode !=0:print(f'转换失败:{result.stderr}')returnFalsereturnTrueexcept FileNotFoundError:print('错误:未找到 pandoc')print('请安装 pandoc:https://pandoc.org/installing.html')returnFalsedefconvert_to_html(input_path:str, output_path:str)->bool:"""使用 pandoc 转换为 HTML"""try: cmd =['pandoc', input_path,'-o', output_path,'--standalone'] result = subprocess.run(cmd, capture_output=True, text=True)if result.returncode !=0:print(f'转换失败:{result.stderr}')returnFalsereturnTrueexcept FileNotFoundError:print('错误:未找到 pandoc')print('请安装 pandoc:https://pandoc.org/installing.html')returnFalsedefmain():iflen(sys.argv)!=3:print('用法:python convert_format.py <input.docx> <output.pdf|txt|html>')print('示例:')print(' python convert_format.py report.docx report.pdf')print(' python convert_format.py report.docx report.txt')print(' python convert_format.py report.docx report.html') sys.exit(1) input_path = sys.argv[1] output_path = sys.argv[2]# 检查输入文件ifnot os.path.exists(input_path):print(f'错误:找不到输入文件 {input_path}') sys.exit(1)# 获取输出格式 output_ext = os.path.splitext(output_path)[1].lower()# 根据格式选择转换方法 success =Falseif output_ext =='.pdf': success = convert_to_pdf(input_path, output_path)elif output_ext =='.txt': success = convert_to_txt(input_path, output_path)elif output_ext =='.html': success = convert_to_html(input_path, output_path)else:print(f'错误:不支持的输出格式 {output_ext}')print('支持的格式:.pdf, .txt, .html') sys.exit(1)if success:print(f'转换成功:{output_path}')else: sys.exit(1)if __name__ =='__main__': main()

6.5 scripts/extract_text.py

#!/usr/bin/env python3""" 提取 Word 文档中的文本内容 用法: python extract_text.py <document.docx> 输出: 生成与输入文件同名的 .txt 文件 """import sys from docx import Document defextract_text(docx_path:str)->str:"""从 Word 文档中提取所有文本""" doc = Document(docx_path)# 收集所有段落的文本 paragraphs =[]for para in doc.paragraphs:if para.text.strip():# 跳过空段落 paragraphs.append(para.text)# 收集表格中的文本 tables_text =[]for table in doc.tables: table_rows =[]for row in table.rows: row_text =[cell.text.strip()for cell in row.cells] table_rows.append(' | '.join(row_text)) tables_text.append('\n'.join(table_rows))# 组合所有文本 result ='\n\n'.join(paragraphs)if tables_text: result +='\n\n=== 表格内容 ===\n\n' result +='\n\n'.join(tables_text)return result defmain():iflen(sys.argv)!=2:print('用法:python extract_text.py <document.docx>')print('示例:python extract_text.py report.docx') sys.exit(1) docx_path = sys.argv[1]try: text = extract_text(docx_path)# 生成输出文件名 output_path = docx_path.replace('.docx','.txt')# 写入文件withopen(output_path,'w', encoding='utf-8')as f: f.write(text)print(f'文本已提取:{output_path}')print(f'共 {len(text)} 个字符')except FileNotFoundError:print(f'错误:找不到文件 {docx_path}') sys.exit(1)except Exception as e:print(f'错误:{e}') sys.exit(1)if __name__ =='__main__': main()

6.6 references/ooxml-reference.md

# OOXML 参考指南 本文档提供 Office Open XML (OOXML) 格式的技术参考,用于深度操作 Word 文档。 ## 什么是 OOXML? OOXML 是 Microsoft Office 2007 及以后版本使用的基于 XML 的文档格式。.docx 文件实际上是一个 ZIP 压缩包,包含多个 XML 文件。 ## 文档结构 document.docx (ZIP 压缩包) ├── [Content_Types].xml # 内容类型定义 ├── _rels/ │ └── .rels # 包级关系 ├── docProps/ │ ├── app.xml # 应用程序属性 │ └── core.xml # 核心属性(作者、标题等) └── word/ ├── document.xml # 文档主要内容 ├── styles.xml # 样式定义 ├── settings.xml # 文档设置 ├── fontTable.xml # 字体表 ├── numbering.xml # 编号定义 └── _rels/ └── document.xml.rels # 文档级关系 ## 常用操作 ### 解压文档 unzip document.docx -d unpacked/ ### 重新打包 cd unpacked/ zip -r ../document-new.docx . ## document.xml 结构 ### 段落 (Paragraph) <w:p> <w:pPr> <!-- 段落属性 --> <w:pStyle w:val="Heading1"/> <!-- 段落样式 --> <w:jc w:val="center"/> <!-- 居中对齐 --> </w:pPr> <w:r> <!-- 文本运行 --> <w:rPr> <!-- 文本属性 --> <w:b/> <!-- 加粗 --> <w:color w:val="FF0000"/> <!-- 红色 --> </w:rPr> <w:t>这是文本内容</w:t> <!-- 文本内容 --> </w:r> </w:p> ### 表格 (Table) <w:tbl> <w:tblPr> <!-- 表格属性 --> <w:tblStyle w:val="TableGrid"/> <w:tblW w:w="5000" w:type="pct"/> <!-- 宽度 50% --> </w:tblPr> <w:tr> <!-- 表格行 --> <w:tc> <!-- 表格单元格 --> <w:p> <w:r> <w:t>单元格内容</w:t> </w:r> </w:p> </w:tc> </w:tr> </w:tbl> ## 常用命名空间 | 前缀 | 命名空间 | 说明 | |-----|---------|------| | w | http://schemas.openxmlformats.org/wordprocessingml/2006/main | Word 主命名空间 | | r | http://schemas.openxmlformats.org/officeDocument/2006/relationships | 关系命名空间 | | wp | http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing | 绘图命名空间 | ## 修订跟踪 ### 插入的文本 <w:ins w:id="1" w:author="作者名" w:date="2024-01-01T00:00:00Z"> <w:r> <w:t>新插入的文本</w:t> </w:r> </w:ins> ### 删除的文本 <w:del w:id="2" w:author="作者名" w:date="2024-01-01T00:00:00Z"> <w:r> <w:delText>被删除的文本</w:delText> </w:r> </w:del> ## 样式引用 ### 段落样式 <w:pStyle w:val="Heading1"/> <!-- 标题 1 --> <w:pStyle w:val="Heading2"/> <!-- 标题 2 --> <w:pStyle w:val="Normal"/> <!-- 正文 --> ### 文本样式 <w:rPr> <w:b/> <!-- 加粗 --> <w:i/> <!-- 斜体 --> <w:u w:val="single"/> <!-- 下划线 --> <w:strike/> <!-- 删除线 --> <w:color w:val="FF0000"/> <!-- 字体颜色 --> <w:sz w:val="24"/> <!-- 字号(半磅)12pt --> <w:rFonts w:ascii="Arial"/> <!-- 字体 --> </w:rPr> ## 页眉页脚 ### 页眉引用 <w:sectPr> <w:headerReference w:type="default" r:id="rId7"/> </w:sectPr> ### 页脚引用 <w:sectPr> <w:footerReference w:type="default" r:id="rId8"/> <w:pgNumType w:start="1"/> <!-- 页码从 1 开始 --> ## 参考资料 - [OOXML 标准文档](https://ecma-international.org/publications-and-standards/standards/ecma-376/) - [python-docx 文档](https://python-docx.readthedocs.io/) - [Office Open XML 简介](https://docs.microsoft.com/en-us/office/open-xml/open-xml-sdk) 

6.6 references/formatting-guide.md

# 格式化指南 本文档提供 Word 文档格式化的最佳实践和高级技巧。 ## 目录 - [样式系统](#样式系统) - [段落格式](#段落格式) - [字符格式](#字符格式) - [列表和编号](#列表和编号) - [表格格式](#表格格式) - [修订跟踪](#修订跟踪) - [评论](#评论) ## 样式系统 ### 内置样式 | 样式名称 | 用途 | 级别 | |---------|------|------| | Title | 文档标题 | 文档 | | Heading 1 | 一级标题 | 大纲级别 1 | | Heading 2 | 二级标题 | 大纲级别 2 | | Heading 3 | 三级标题 | 大纲级别 3 | | Normal | 正文 | 正文 | | Quote | 引用 | 正文 | | Code | 代码 | 正文 | ### 使用样式的最佳实践 1. **始终使用样式而非直接格式化** - ❌ 不要:选中文本 → 点击加粗 → 设置字号 - ✅ 要:选中文本 → 应用 "Heading 1" 样式 2. **修改样式而非文本** - 右键样式 → 修改 → 应用到所有使用该样式的文本 3. **创建自定义样式** - 样式窗格 → 新建样式 → 定义格式 → 保存 ## 段落格式 ### 对齐方式 from docx import Document from docx.enum.text import WD_ALIGN_PARAGRAPH doc = Document() para = doc.add_paragraph('居中对齐的文本') para.alignment = WD_ALIGN_PARAGRAPH.CENTER # 其他选项: # WD_ALIGN_PARAGRAPH.LEFT # 左对齐 # WD_ALIGN_PARAGRAPH.RIGHT # 右对齐 # WD_ALIGN_PARAGRAPH.JUSTIFY # 两端对齐 ### 行距和段间距 from docx.shared import Pt para = doc.add_paragraph('示例段落') para.paragraph_format.line_spacing = 1.5 # 1.5 倍行距 para.paragraph_format.space_before = Pt(12) # 段前 12 磅 para.paragraph_format.space_after = Pt(12) # 段后 12 磅 ### 缩进 from docx.shared import Inches para = doc.add_paragraph('首行缩进的段落') para.paragraph_format.first_line_indent = Inches(0.5) # 首行缩进 0.5 英寸 para.paragraph_format.left_indent = Inches(0.5) # 左缩进 para.paragraph_format.right_indent = Inches(0.5) # 右缩进 ## 字符格式 ### 字体设置 from docx.shared import Pt para = doc.add_paragraph() run = para.add_run('格式化的文本') run.bold = True # 加粗 run.italic = True # 斜体 run.underline = True # 下划线 run.font.size = Pt(12) # 字号 12pt run.font.name = 'Arial' # 英文字体 run.font.color.rgb = RGBColor(255, 0, 0) # 红色 ### 中文字体 from docx.oxml.ns import qn run = para.add_run('中文文本') run.font.name = 'SimSun' # 设置英文字体 run._element.rPr.rFonts.set(qn('w:eastAsia'), '宋体') # 设置中文字体 ## 列表和编号 ### 项目符号列表 doc.add_paragraph('项目 1',) doc.add_paragraph('项目 2',) doc.add_paragraph('项目 3',) ### 编号列表 doc.add_paragraph('第一步',) doc.add_paragraph('第二步',) doc.add_paragraph('第三步',) ### 多级列表 # 一级 doc.add_paragraph('第一章',) # 二级 doc.add_paragraph('1.1 节',) doc.add_paragraph('1.2 节',) # 三级 doc.add_paragraph('1.2.1 小节',) ## 表格格式 ### 创建表格 from docx import Document from docx.shared import Inches doc = Document() table = doc.add_table(rows=3, cols=3) table.style = 'Light Grid Accent 1' # 表格样式 # 设置列宽 table.columns[0].width = Inches(1.5) table.columns[1].width = Inches(2.0) table.columns[2].width = Inches(1.5) # 填充数据 headers = ['姓名', '部门', '职位'] 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.bold = True ### 合并单元格 # 横向合并 cell_a = table.rows[0].cells[0] cell_b = table.rows[0].cells[1] cell_a.merge(cell_b) # 纵向合并 cell_a = table.rows[0].cells[0] cell_b = table.rows[1].cells[0] cell_a.merge(cell_b) ## 修订跟踪 ### 启用修订跟踪 from docx import Document doc = Document() # 添加修订标记的文本 para = doc.add_paragraph() # 插入的文本(带修订标记) run = para.add_run('这是新添加的文本') run.font.highlight_color = 7 # 浅绿色高亮表示插入 # 或使用 OOXML 直接操作(需要更复杂的处理) ### 接受/拒绝修订 使用 python-docx 库直接处理修订跟踪比较复杂,建议使用 LibreOffice 命令行: # 接受所有修订 soffice --headless --accept-all-revisions input.docx # 拒绝所有修订 soffice --headless --reject-all-revisions input.docx ## 评论 ### 添加评论 from docx import Document from docx.shared import Pt doc = Document() para = doc.add_paragraph('这是一段需要评论的文本') # python-docx 不直接支持评论 # 需要使用 OOXML 操作或 comtypes(Windows) ### Windows 平台添加评论 import win32com.client word = win32com.client.Dispatch("Word.Application") word.Visible = False doc = word.Documents.Open("document.docx") selection = word.Selection # 选择文本 selection.Find.Execute("需要评论的文本") # 添加评论 doc.Comments.Add(selection.Range, "这是评论内容") doc.Save() doc.Close() word.Quit() ## 页面设置 ### 页面大小和方向 from docx import Document from docx.shared import Inches from docx.enum.section import WD_ORIENT doc = Document() # 获取第一节 section = doc.sections[0] # 设置页面大小 section.page_width = Inches(8.5) section.page_height = Inches(11) # 设置横向 section.orientation = WD_ORIENT.LANDSCAPE ### 页边距 section = doc.sections[0] section.top_margin = Inches(1) section.bottom_margin = Inches(1) section.left_margin = Inches(1.25) section.right_margin = Inches(1.25) ## 页眉页脚 ### 添加页眉 from docx import Document doc = Document() # 获取默认页眉 header = doc.sections[0].header # 添加页眉内容 para = header.paragraphs[0] para.text = "文档标题" para.alignment = WD_ALIGN_PARAGRAPH.CENTER ### 添加页脚和页码 from docx import Document from docx.enum.text import WD_ALIGN_PARAGRAPH doc = Document() footer = doc.sections[0].footer # 添加页码(需要域代码) para = footer.paragraphs[0] para.alignment = WD_ALIGN_PARAGRAPH.CENTER # 使用域代码添加页码 run = para.add_run() run._element.append(parse_xml(r'<w:fldSimple xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" w:instr="PAGE"/>')) ## 参考资料 - [python-docx 官方文档](https://python-docx.readthedocs.io/) - [Word 样式指南](https://support.microsoft.com/en-us/office/styles-in-word-9db4c0f6-7be0-4d37-9383-929a6a79f670) - [OOXML 格式规范](https://ecma-international.org/publications-and-standards/standards/ecma-376/) 

6.7 assets/letterhead-template.docx

[公司 Logo] 公司名称 __________________________________________________ [在此处添加正文内容] __________________________________________________ 地址:XXX | 电话:XXX | 邮箱:XXX 

Read more

Obsidian同步太折腾?试试坚果云官方插件:免WebDAV配置,支持Git级冲突合并

Obsidian同步太折腾?试试坚果云官方插件:免WebDAV配置,支持Git级冲突合并

Obsidian 作为本地 Markdown 笔记软件的王者,其“数据掌握在自己手中”的理念深受开发者喜爱。但作为一名多端用户,同步问题一直是最大的痛点。官方 Sync 服务太贵,WebDAV 配置繁琐且不仅容易断连,还经常遇到笔记冲突。 终于,大家催了无数遍的 Obsidian x 坚果云「官方同步插件 Nutstore Sync」 正式上架社区插件市场了! 这不仅仅是一个同步工具,更是一套完整的移动端解决方案。 为什么推荐这款官方插件? 1. 告别复杂的 WebDAV 配置(SSO单点登录) 以前配置 WebDAV,你需要生成应用密码、复制服务器地址、担心端口被封。 现在,安装 Nutstore Sync 后,直接点击“登录”,通过单点登录 授权,一键回调到 Obsidian,配置过程缩短到秒级,新手极其友好。

Windows软件安装报错?3分钟搞定Webview2和.NET4.8缺失问题(附C盘权限获取技巧)

Windows软件安装报错终极指南:从Webview2到.NET4.8的完整解决方案 每次安装新软件时遇到"缺少Webview2 Runtime"或".NET Framework 4.8未安装"的报错提示,是不是让你感到无比烦躁?这些看似复杂的系统组件缺失问题,其实都有简单直接的解决方法。本文将带你一步步彻底解决这些安装障碍,同时分享几个鲜为人知的C盘权限管理技巧,让你的软件安装过程从此畅通无阻。 1. 理解核心组件:Webview2和.NET4.8为何如此重要 现代Windows软件越来越依赖这些基础运行环境。Microsoft Edge WebView2是一个嵌入式浏览器组件,允许应用程序显示网页内容,而.NET Framework 4.8则是微软开发的软件开发平台,许多程序都基于它构建。当你的系统缺少这些组件时,就像试图在没有地基的房子上盖楼——注定会失败。 常见症状包括: * "Microsoft Edge WebView2 Runtime未安装"错误提示

基于Java Web的毕业设计选题系统设计与实现:新手入门实战指南

每到毕业季,高校的毕业设计选题环节总是让管理员和学生们头疼不已。传统的线下或简单线上流程,常常暴露出几个典型问题:系统一开放,学生们蜂拥而至,经常出现“秒杀”式的竞争,导致服务器卡顿甚至崩溃;好不容易选上了,却可能因为网络延迟或并发问题,出现“一题多选”或“超选”的数据混乱;老师和学生之间的信息不通畅,选题状态不透明,沟通成本极高。这些问题背后,其实都指向了系统在并发控制、数据一致性和用户体验上的缺失。 作为一个Java Web的初学者,要独立解决这些问题似乎很有挑战。但别担心,我们可以通过一个结构清晰、技术栈成熟的项目来逐一攻克。下面,我就结合自己搭建“毕业设计选题系统”的实战经验,从零开始,带你走一遍核心的设计与实现思路。 1. 为什么选择 Spring Boot + MyBatis? 在开始敲代码之前,技术选型是第一步。Java Web的框架组合很多,比如经典的SSH、SSM,还有新兴的Spring Boot搭配JPA或MyBatis-Plus。对于新手来说,我强烈推荐

学得会、做得出、能展示!12493+基于Web的校园二手商品交易系统设计与实现 全套资料打包送,学习更高效!

学得会、做得出、能展示!12493+基于Web的校园二手商品交易系统设计与实现 全套资料打包送,学习更高效!

基于Web的校园二手商品交易系统设计与实现 摘  要 随着互联网技术的快速发展,校园内二手商品的交易需求日益增长。因此,本研究引入信息化技术设计并实现一套高效简便且功能齐全的校园二手商品交易系统,以提升校园二手交易的效率和可靠性。该系统基于Web技术,后端选择Java作为编程语言,并采用了Spring Boot框架以确保高效和稳定的性能表现。系统前端则是利用了HTML、CSS及JavaScript等技术来构建用户交互界面,提供直观且易于操作的用户体验。同时以MySQL数据库作为数据存储核心,并运用RESTful API实现前后端分离的架构。系统主要面向普通用户和管理员两大不同角色,实现了包括系统用户管理、在线反馈管理、系统管理、公告通知管理、资源管理、交流管理、商城管理、聊天中心及数据统计等核心功能,有效提升二手交易管理效率和服务质量。最终经过功能验证和性能测试,确保系统在实际应用中的可行性和高效性。本系统的实施为高校学生提供一个便利安全且可靠的二手交易平台和管理工具,不仅能够有效整合并管理用户、商品与订单等信息,提高二手交易管理的便捷性与效率,还提供了实时的数据分析和反馈机制,为