CommunityProgramación y desarrollogithub.com

docx

Crea, lee, edita y manipula documentos Word (.docx) y plantillas (.dotx) con formato profesional.

¿Qué es docx?

Esta habilidad permite a un agente de IA crear, editar, leer y manipular documentos Word (.docx) y plantillas (.dotx). Es útil para generar informes, cartas, memorandos, documentos profesionales con formato (índices, encabezados, numeración de páginas, membretes), extraer o reorganizar contenido de archivos .docx/.dotx, insertar o reemplazar imágenes, realizar buscar y reemplazar, gestionar cambios controlados o comentarios, y convertir contenido a un documento Word pulido. Funciona mediante scripts de Node.js (docx-js) para crear documentos nuevos, o descomprimiendo el archivo y editando el XML subyacente para modificaciones avanzadas. También utiliza herramientas como Pandoc para leer contenido y LibreOffice para convertir formatos o validar. Soporta la edición de documentos existentes, la gestión de cambios controlados con validación de autor, la inserción de comentarios, y la conversión de documentos .doc (legacy) a .docx. La habilidad incluye scripts auxiliares para fusionar fragmentos de texto en el XML, validar contra esquemas XSD, y aceptar cambios controlados.

Compatible con~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/anthropics/skills/tree/main/skills/docx

Installed? Explore more Programación y desarrollo skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

Preguntar en tu IA favorita

Abre un nuevo chat con esta habilidad de agente ya precargada.

Documentación

Creación, edición y análisis de DOCX

Un archivo .docx es un archivo ZIP que contiene archivos XML. Elige tu enfoque según la tarea:

TareaEnfoque
Crear un documento nuevoEscribir un script con docx (npm) — ver errores comunes abajo
Editar un documento existenteunzip → editar word/document.xml → zip (docx-js no puede abrir archivos existentes)
Leer contenidopandoc -t markdown file.docx

Las rutas de los scripts a continuación son relativas al directorio de esta habilidad.

Creación con docx-js — errores comunes

docx ya está preinstalado — no ejecutes npm install primero; escribe el script y usa require('docx') directamente. Solo si ese require falla: npm install docx. El modelo conoce la API; estos son los puntos problemáticos:

  • El tamaño de página predeterminado es A4. Para Carta EE. UU. configura page: { size: { width: 12240, height: 15840 } } (DXA; 1440 = 1″).
  • Horizontal: pasa las dimensiones verticales y orientation: PageOrientation.LANDSCAPE — docx-js intercambia ancho/alto internamente.
  • Las tablas necesitan anchos duales: configura columnWidths en la tabla Y width en cada celda, ambos en WidthType.DXA (PORCENTAJE falla en Google Docs). Los anchos de las columnas deben sumar el ancho de la tabla.
  • Sombreado de tabla: usa ShadingType.CLEAR, nunca SOLID (se renderiza negro).
  • Listas: nunca insertes • literalmente; usa una configuración de numbering con LevelFormat.BULLET.
  • ImageRun requiere type: ("png", "jpg", …).
  • PageBreak debe estar dentro de un Paragraph.
  • Nunca uses \n — usa elementos Paragraph separados.
  • TOC: los encabezados deben usar los HeadingLevel.* integrados; los estilos de encabezado personalizados necesitan outlineLevel configurado o no aparecerán.
  • No uses una tabla como regla horizontal — usa mejor un borde inferior de párrafo.
  • Línea de puntos / alineado a la derecha en la misma línea: usa PositionalTab (alignment: PositionalTabAlignment.RIGHT, leader: PositionalTabLeader.DOT) dentro de un TextRun, no puntos literales ni rellenos con espacios.

Verificar la salida

Después de escribir un .docx, renderízalo y míralo:

python scripts/office/soffice.py --headless --convert-to pdf output.docx
pdftoppm -jpeg -r 100 output.pdf page
ls page-*.jpg   # luego Leer las imágenes

pdftoppm rellena con ceros los números de página hasta el ancho del recuento de páginas (page-01.jpg…page-12.jpg).

Editar documentos existentes

Los archivos .doc heredados deben convertirse primero: python scripts/office/soffice.py --headless --convert-to docx file.doc.

unzip -q doc.docx -d unpacked/
find unpacked -type l -delete   # eliminar entradas de enlace simbólico — el docx de terceros no es fiable
python scripts/merge_runs.py unpacked/   # fusiona fragmentos de texto para que el texto sea buscable
# editar unpacked/word/document.xml in situ — NO reformatear ni embellecer
(cd unpacked && rm -f ../out.docx && zip -Xr ../out.docx .)
python scripts/office/validate.py out.docx --original doc.docx   # comprobaciones XSD; --auto-repair corrige problemas comunes
# ¿cambios controlados? añade --author "<el nombre bajo el que hiciste cambios>" para verificar que cada edición está registrada

Word divide el texto en muchas ejecuciones <w:r> (identificadores de revisión, marcadores de corrección ortográfica), por lo que una frase que ves en el documento a menudo no existe como cadena contigua en el XML. merge_runs.py fusiona ejecuciones adyacentes con el mismo formato en word/document.xml sin cambiar el contenido ni el renderizado; también acepta un .docx directamente (python scripts/merge_runs.py doc.docx -o merged.docx).

Cambios controlados: al hacer marcas de cambio, valida con --author "<el nombre bajo el que hiciste cambios>" (necesita --original) — informa de cualquier texto que hayas cambiado sin un <w:ins>/<w:del> alrededor, lo cual es fácil de hacer accidentalmente e invisible en la vista aceptada. Envuelve las ejecuciones en <w:ins>/<w:del> con atributos w:id, w:author, w:date. Dentro de <w:del>, el elemento de texto es <w:delText>, no <w:t>. Una marca de párrafo eliminada (<w:pPr><w:rPr><w:del w:id=".." w:author=".." w:date="../></w:rPr></w:pPr>) significa "fusiona este párrafo con el siguiente" — por lo tanto, eliminar un párrafo por completo es eso más un <w:del> alrededor de cada ejecución. El <w:del/> debe ir antes de los otros hijos de rPr; su orden está impuesto por el esquema.

Para producir una copia limpia con todos los cambios controlados aceptados: python scripts/accept_changes.py in.docx out.docx.

Aceptar una marca de párrafo eliminada debería unir ese párrafo al siguiente, por lo que un párrafo cuyas ejecuciones están todas eliminadas desaparece. Word hace esto; accept_changes.py y pandoc --track-changes=accept no siempre lo hacen. Ambos fallan de la misma manera: eliminan el texto eliminado pero dejan el párrafo vacío, que se lee como una viñeta vacía perdida cuando estaba auto numerada:

  • pandoc --track-changes=accept nunca une los párrafos.
  • accept_changes.py (LibreOffice) los une correctamente, excepto cuando el párrafo eliminado va seguido de un párrafo espaciador vacío.

Una viñeta vacía en cualquiera de las vistas es un artefacto de esa vista, no un defecto en el documento. Verifica las eliminaciones de párrafos en el XML.

Comentarios

Los comentarios requieren seis archivos vinculados entre sí. Usa el ayudante — modo directorio cuando también vayas a editar document.xml (ahorra un ciclo de descompresión/recompresión), modo .docx directo en caso contrario:

# Contra un directorio ya descomprimido (preferido al colocar también marcadores)
python scripts/comment.py unpacked/ "El límite de tarifas y gastos es demasiado bajo"
python scripts/comment.py unpacked/ "De acuerdo" --parent 0

# Contra un .docx directamente
python scripts/comment.py contract.docx "Este límite es demasiado bajo" -o annotated.docx

El script escribe comments.xml, commentsExtended.xml, commentsIds.xml, commentsExtensible.xml, las relaciones y las anulaciones de tipo de contenido. Los ID de comentario se asignan automáticamente. Luego imprime el fragmento <w:commentRangeStart>/<w:commentRangeEnd>/<w:commentReference> para añadir a word/document.xml para que el comentario se ancle a un texto específico — hasta que coloques esos marcadores, el comentario existe pero no es visible.

Dependencias

docx (npm, preinstalado — instalar solo si falla require('docx')) · pandoc · LibreOffice (soffice) · pdftoppm (Poppler)

Individual skills in this repo

This repo contains 19 individual skills — each has its own dedicated page.

academy-guide

Stop and check this skill before finishing any reply to a question about how to use Claude or a Claude product — it recommends matching courses, tutorials, and use cases from Claude Academy (academy.claude.com), Anthropic's learning hub. Trigger on: "how do I", "how can I", "getting started with", "what can Claude do", "teach me", "learn to use"; questions about artifacts, projects, skills, plugins, connectors, MCP; requests about rolling Claude out to a team, class, or organization; and any ask for training materials, onboarding content, or learning resources. Use it when the user is learning how to use a feature or product — not when they are mid-task and just want the task done. This skill composes with other skills: after consulting product documentation to answer how a Claude feature works, also check here for a matching course or tutorial — a docs-grounded answer and an Academy recommendation belong together. Only recommend on a strong match; never invent Academy content.

algorithmic-art

Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code, generative art, algorithmic art, flow fields, or particle systems. Create original algorithmic art rather than copying existing artists

anthropics/template-skill

Replace with description of the skill and when Claude should use it.

brand-guidelines

Applies Anthropic's official brand colors and typography to any sort of artifact that may benefit from having Anthropic's look-and-feel. Use it when brand colors or style guidelines, visual formatting, or company design standards apply.

canvas-design

Create beautiful visual art in .png and .pdf documents using design philosophy. You should use this skill when the user asks to create a poster, piece of art, design, or other static piece. Create original visual designs, never copying existing artists

claude-api

|-

discernment-nudge

After you give a substantive answer or draft that the user may act on — advice or recommendations, drafted artifacts such as goals, plans, pitches, proposals, or emails, estimates or projections, analysis or interpretation of data, factual claims they may rely on, or a multi-step argument — invoke this skill BEFORE finalizing your reply and then, if it applies, append 2-3 short follow-up questions, each tied to something specific in what you just produced, that help the user check key facts, probe the reasoning or assumptions, and notice missing context. Do this at most once per conversation. Skip it when the user asked a trivial how-to or simple lookup, wants a purely educational explanation, asked you only to format, convert, or assemble a file from content they provided, is writing code they will run, is doing creative writing or casual chat, or already asked you to double-check, cite, or review — the skill file explains these boundaries and the exact output format.

doc-coauthoring

Guide users through a structured workflow for co-authoring documentation. Use when user wants to write documentation, proposals, technical specs, decision docs, or similar structured content. This workflow helps users efficiently transfer context, refine content through iteration, and verify the doc works for readers. Trigger when user mentions writing docs, creating proposals, drafting specs, or similar documentation tasks.

frontend-design

Guidance for distinctive, intentional visual design when building new UI or reshaping an existing one. Helps with aesthetic direction, typography, and making choices that don't read as templated defaults.

internal-comms

A set of resources to help me write all kinds of internal communications, using the formats that my company likes to use. Claude should use this skill whenever asked to write some sort of internal communications (status reports, leadership updates, 3P updates, company newsletters, FAQs, incident reports, project updates, etc.).

mcp-builder

Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when building MCP servers to integrate external APIs or services, whether in Python (FastMCP) or Node/TypeScript (MCP SDK).

pdf

Use this skill whenever the user wants to do anything with PDF files. This includes reading or extracting text/tables from PDFs, combining or merging multiple PDFs into one, splitting PDFs apart, rotating pages, adding watermarks, creating new PDFs, filling PDF forms, encrypting/decrypting PDFs, extracting images, and OCR on scanned PDFs to make them searchable. If the user mentions a .pdf file or asks to produce one, use this skill.

pptx

Use this skill any time a .pptx or .potx file is involved in any way — as input, output, or both. This includes: creating slide decks, pitch decks, or presentations; reading, parsing, or extracting text from any .pptx or .potx file (even if the extracted content will be used elsewhere, like in an email or summary); editing, modifying, or updating existing presentations; combining or splitting slide files; working with templates (.potx), layouts, speaker notes, or comments. Trigger whenever the user mentions "deck," "slides," "presentation," or references a .pptx or .potx filename, regardless of what they plan to do with the content afterward. If a .pptx or .potx file needs to be opened, created, or touched, use this skill.

skill-creator

Create new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an existing skill, run evals to test a skill, benchmark skill performance with variance analysis, or optimize a skill

slack-gif-creator

Knowledge and utilities for creating animated GIFs optimized for Slack. Provides constraints, validation tools, and animation concepts. Use when users request animated GIFs for Slack like

theme-factory

Toolkit for styling artifacts with a theme. These artifacts can be slides, docs, reportings, HTML landing pages, etc. There are 10 pre-set themes with colors/fonts that you can apply to any artifact that has been creating, or can generate a new theme on-the-fly.

webapp-testing

Toolkit for interacting with and testing local web applications using Playwright. Supports verifying frontend functionality, debugging UI behavior, capturing browser screenshots, and viewing browser logs.

web-artifacts-builder

Suite of tools for creating elaborate, multi-component claude.ai HTML artifacts using modern frontend web technologies (React, Tailwind CSS, shadcn/ui). Use for complex artifacts requiring state management, routing, or shadcn/ui components - not for simple single-file HTML/JSX artifacts.

xlsx

Use this skill any time a spreadsheet file is the primary input or output. This means any task where the user wants to: open, read, edit, or fix an existing .xlsx, .xlsm, .xltx, .csv, or .tsv file (e.g., adding columns, computing formulas, formatting, charting, cleaning messy data); create a new spreadsheet from scratch or from other data sources; or convert between tabular file formats. Trigger especially when the user references a spreadsheet file by name or path — even casually (like "the xlsx in my downloads") — and wants something done to it or produced from it. Also trigger for cleaning or restructuring messy tabular data files (malformed rows, misplaced headers, junk data) into proper spreadsheets. The deliverable must be a spreadsheet file. Do NOT trigger when the primary deliverable is a Word document, HTML report, standalone Python script, database pipeline, or Google Sheets API integration, even if tabular data is involved.

Skills relacionados