← Office documents
Office·Format guide
All tools

Office Open XML: .docx, .xlsx, .pptx

Word, Excel and PowerPoint documents since Office 2007 are Office Open XML (ECMA-376, ISO/IEC 29500): a ZIP archive of XML parts tied together by relationships. The Office documents tool shows that structure — the paragraphs with their formatting, the cells, the slides and shapes, every part and relationship — and lets you change it; it never draws a page, a sheet or a slide.

Contents

  1. The package (OPC)
  2. WordprocessingML
  3. Word's styles and direct formatting
  4. SpreadsheetML
  5. PresentationML and its inheritance
  6. Macros, embedded objects, ActiveX
  7. What deserves attention
  8. What the editor changes
  9. What the tool shows, and its limits
  10. The libraries

The package (Open Packaging Conventions)

ECMA-376 Part 2. A part is a ZIP entry; its name is a path (case-insensitive, written without the leading / in the ZIP). Three things make a ZIP a package:

PartWhat it does
[Content_Types].xmlThe content type of every part: <Default Extension="xml" ContentType="…"/> for an extension, <Override PartName="/word/document.xml" ContentType="…"/> for one part (an Override wins). Office decides what a part is from this, never from its name.
_rels/.relsThe package relationships: officeDocument (the main part), core-properties, extended-properties, custom-properties, thumbnail, the digital signature origin.
dir/_rels/name.relsThe relationships of the part dir/name: <Relationship Id="rId4" Type="…/image" Target="media/image1.png"/>. Targets are relative to the source's folder (../media/x.png), or absolute (/word/x.xml), or, with TargetMode="External", a URL or file path outside the package. The XML refers to relationships by id (r:id, r:embed, r:link).

The properties: docProps/core.xml (Dublin Core: title, creator, lastModifiedBy, revision, created, modified, lastPrinted…), docProps/app.xml (Application, AppVersion, Company, Manager, Template, page and word counts, TitlesOfParts) and docProps/custom.xml (named properties, often from SharePoint or document management). Other package-level parts: customXml/item*.xml (data stores, with itemProps*.xml naming their schemas), docProps/thumbnail.*, _xmlsignatures/ (XML digital signatures: each sig*.xml lists the parts it signs by URI and digest).

WordprocessingML

The main part (word/document.xml) holds w:body: a sequence of paragraphs (w:p) and tables (w:tbl → w:tr → w:tc, whose content is again paragraphs and tables), possibly inside content controls (w:sdt). A paragraph holds runs (w:r: text with one formatting), inside w:hyperlink, tracked changes, fields or content controls. A run holds w:t (text), w:tab, w:br, w:drawing (DrawingML pictures, charts, SmartArt, text boxes), w:pict and w:object (VML and OLE), w:fldChar/w:instrText (fields), note and comment references.

Element or partMeaning
w:pPr / w:rPrParagraph and run properties: the direct formatting. w:pPr also holds the style (w:pStyle), numbering (w:numPr), a section break (w:sectPr) and the paragraph mark's own run properties (w:pPr/w:rPr).
w:sectPrA section: page size and margins, columns, the header and footer parts it uses (w:headerReference/w:footerReference of type default, first, even). The last one is the body's own; the others end the paragraph that holds them.
fieldsw:fldSimple w:instr="…", or a complex field: w:fldChar begin, the instruction in w:instrText, separate, the result runs, end. The instruction's first word is its type (PAGE, TOC, HYPERLINK, INCLUDEPICTURE, DDEAUTO…).
tracked changesw:ins, w:del (with w:delText), w:moveFrom/w:moveTo, and the previous properties in w:rPrChange, w:pPrChange, w:sectPrChange, w:tblPrChange…, each with w:author and w:date. An inserted or deleted paragraph mark is w:ins/w:del inside w:pPr/w:rPr; an inserted row is inside w:trPr.
comments.xmlw:comment (id, author, initials, date) with paragraphs; the commented text lies between w:commentRangeStart and w:commentRangeEnd, and a run holds w:commentReference. Replies and "resolved" are in commentsExtended.xml (keyed by the w14:paraId of each comment's last paragraph); commentsIds.xml, commentsExtensible.xml and people.xml add durable ids and accounts.
footnotes.xml, endnotes.xmlw:footnote/w:endnote by id; ids −1 and 0 are the separator and continuation separator.
numbering.xmlw:abstractNum (a definition: up to nine w:lvl with start, format, level text such as %1.%2., indentation) and w:num (a list, by numId, pointing at a definition, with level overrides). Paragraphs name a numId and level (ilvl), directly or through their style.
settings.xmlDocument settings: w:attachedTemplate (a relationship to the template), w:documentProtection, w:trackRevisions, w:updateFields, w:mailMerge, w:docVars, w:rsids (one id per editing session), compatibility settings.
w:vanishHidden text: present in the file, not shown or printed by default.

Word's styles and direct formatting

word/styles.xml holds the document defaults (w:docDefaults: w:rPrDefault, w:pPrDefault), the latent styles (built-in styles not written out, with their gallery settings), and the styles: paragraph, character, table and numbering styles, each with an id, a name, and optionally w:basedOn (it inherits from that style), w:next, w:link (a paragraph style and a character style that are one style in Word's interface), and its own w:pPr/w:rPr/w:tblPr. One style of each type is the default (w:default="1"): Normal, Default Paragraph Font, Normal Table.

The value of a property is worked out in this order (ECMA-376 17.7.2); each level overrides the ones before it, attribute by attribute for spacing and indentation:

  1. the document defaults;
  2. the table style (for paragraphs in a table), with its basedOn chain;
  3. the numbering level's paragraph properties (for list items);
  4. the paragraph style, after the styles it is based on (no w:pStyle: the default paragraph style);
  5. for runs, the character style (w:rStyle), after its bases;
  6. direct formatting: the w:pPr and w:rPr written on the paragraph and the run.

Toggle properties (bold, italic, caps, small caps, strike, double strike, hidden, outline, shadow, emboss, imprint) behave differently in styles (17.7.3): a true value in the paragraph style and another in the character style cancel out; direct formatting sets them outright. So <w:b w:val="0"/> on a run in a Heading 1 paragraph turns bold off whatever the style says.

Direct formatting is what makes documents hard to restyle: a paragraph that looks like a heading because of a 16 pt bold run, not because of its style, won't follow a style change. The Document tab shows, for every paragraph, its style as a blue chip and its direct formatting as orange chips (dashed for the paragraph mark); the formatting pane lists every property's effective value and the level it comes from, with what it overrides.

SpreadsheetML

Part or elementMeaning
xl/workbook.xmlsheets/sheet (name, sheetId, state: visible, hidden or veryHidden, and the relationship to the sheet part — a worksheet, chart sheet, dialog sheet or an Excel 4.0 macro sheet), definedNames (named formulas; localSheetId for one sheet; hidden; Excel's own _xlnm.Print_Area…), workbookProtection (lockStructure, a salted hash with its algorithm and spin count, or the old 16-bit workbookPassword), calcPr, externalReferences, pivotCaches.
xl/sharedStrings.xmlText is stored once: <si><t>…</t></si> (or rich runs r/t); a cell with t="s" holds the index.
xl/styles.xmlnumFmts (custom number formats from id 164; 0–49 are built in), fonts, fills, borders, cellXfs (the cell formats a cell's s attribute indexes, combining a number format, font, fill, border, alignment, protection), cellStyles, dxfs (formats for conditional formatting).
worksheetsheetData/row/c: r (address), t (n number, s shared string, inlineStr, str formula string, b boolean, e error, d date), s (style), f (formula; t="shared" with ref and si: written once and reused with moved references by the other cells of the range; t="array"), v (the cached value). Then merged cells, hyperlinks, data validation, conditional formatting, sheetProtection, and relationships to tables, comments (and the VML that draws them), drawings, pivot tables, query tables, controls.
externalLink*.xmlAnother workbook (externalBook, with an external relationship to its path or URL and cached values), a DDE link (ddeLink ddeService ddeTopic) or an OLE link. Formulas refer to them as [1]Sheet!A1.
connections.xmlData connections: ODBC/OLE DB (dbPr connection command), web queries (webPr url), text files; refreshOnLoad, savePassword. Query tables (queryTable*.xml) place their results in sheets.

PresentationML and its inheritance

ppt/presentation.xml lists the masters (sldMasterIdLst), the slides in order (sldIdLst: an id and a relationship), the slide and notes sizes, sections (an extension), custom shows and defaultTextStyle. A slide (p:sld, show="0" when hidden) holds a shape tree: p:sp (shapes and text boxes, often placeholders p:ph type idx), p:pic, p:graphicFrame (tables, charts, SmartArt, OLE objects), p:grpSp, p:cxnSp. Text is DrawingML: p:txBody → a:p (with a:pPr, level lvl) → a:r (a:rPr attributes sz b i u, children a:solidFill, a:latin, a:hlinkClick) → a:t.

Each slide uses a layout (a relationship), each layout a master, each master a theme. A run's formatting comes from, in order:

  1. the run's own a:rPr (direct formatting);
  2. the shape's a:lstStyle for the paragraph's level (a:lvl1pPr … a:lvl9pPr, their a:defRPr);
  3. for a placeholder: the layout's placeholder with the same index (or type), then the master's placeholder of that type;
  4. the master's text styles: p:titleStyle for titles, p:bodyStyle for body, subtitle and content placeholders, p:otherStyle for the rest; text that isn't in a placeholder takes the presentation's defaultTextStyle;
  5. the theme's fonts, referred to as +mj-lt (major, headings) and +mn-lt (minor, body).

Notes are slides of their own (notesSlide*.xml, related from the slide); comments are comments/comment*.xml with commentAuthors.xml (or the modern modernComment_*.xml with authors.xml). Links and actions are a:hlinkClick/a:hlinkMouseOver on runs and on shapes: a relationship (URL, file, slide) and an action such as ppaction://program (start a program), ppaction://macro?name=…, ppaction://ole?verb=0, ppaction://hlinksldjump. Audio and video are pictures with a:videoFile/a:audioFile r:link and p14:media r:embed, embedded or linked.

Macros, embedded objects, ActiveX

What deserves attention

FindingWhy
VBA macros, XLM macro sheets, Auto_Open names, actions that run programs or macros, shapes with macrosCode that runs with the user's rights once macros are enabled (or, for some, when clicked).
Remote template (attachedTemplate with an external target)Word fetches the template when the document opens; a macro-enabled template brings its macros: template injection, used because the document itself carries no macro.
Other external relationshipsImages, OLE links, frames, subdocuments, linked media and workbook links are fetched or followed; a UNC path (\\server\share, file://server/) makes Windows authenticate to that server (NTLM hash leak). Hyperlinks are listed as information: they need a click.
DDE / DDEAUTO fields, DDE linksDynamic Data Exchange starts the program it names (cmd.exe…), with a prompt; DDEAUTO asks when the document opens.
INCLUDETEXT, INCLUDEPICTURE, LINK, IMPORT fields; w:updateFieldsFields that read other files or URLs when they update.
Embedded OLE objects and packages, ActiveX, embedded fontsContent handled by other programs or parsers.
Data connections, query tables, Power Query (DataMashup), pivot caches that refresh on openNetwork and database access, sometimes with credentials in the connection string.
veryHidden sheets, hidden sheets and names, hidden text, hidden slides and shapes, notes, glossary documentsContent a reader doesn't see. A veryHidden sheet isn't even listed by Excel's Unhide dialog.
Tracked changes, commentsEarlier text (deleted words stay in the file) and authors' names.
Personal informationcreator, lastModifiedBy, lastPrinted, Company, Manager, a template path naming a user account, custom properties, people parts, document variables, revision ids.
Custom XML parts, digital signaturesData not shown in the document; which parts a signature covers (the digests aren't checked here; any edit saved by this tool invalidates a signature).
DOCTYPE in a partOffice ignores DTDs; a DOCTYPE with an external entity is the shape of an XXE attack on tools that do resolve entities (lib/xml-tree.js never does: &entity; stays text).
Package and ZIP odditiesParts no relationship points at (Office ignores them; they can carry data), parts without content type, relationships to missing parts, executable extensions, names that appear twice, unsafe paths, data before or after the ZIP (polyglots), unusual compression.

What the editor changes

Edits change the parts' XML trees in memory; every edit is one undo step, and nothing is written until Save. Saving rebuilds the ZIP in the same order: parts that weren't changed are copied as their compressed bytes (byte-identical); changed XML parts are serialized again (their text is the same apart from the edit, though entity spellings and quotes may be normalised); new and replaced parts are compressed anew. The rebuilt file is opened again and every part compared with what was meant before it is written — back to the opened file when the browser allows (File System Access), else to a chosen file, else as a download with the same name (the extension follows the content: .docm becomes .docx once macros are removed).

EditWhat changes
Clear direct formatting (Word)The paragraph's w:pPr loses every child but w:pStyle, w:sectPr, w:pPrChange, w:cnfStyle and (by default) w:numPr; each run's w:rPr keeps only w:rStyle, w:lang, w:rtl, w:cs and tracked-change records; the paragraph mark's w:rPr likewise. Empty containers go. A single property can be removed from its chip (×) or, attribute by attribute for spacing and indentation, from the formatting pane.
Set stylew:pStyle w:val is set (created first in w:pPr), or removed for the default style.
Accept / reject tracked changesAccepting an insertion keeps its runs and drops the wrapper; accepting a deletion removes it; rejecting does the opposite (w:delText becomes w:t); a rejected w:rPrChange/w:pPrChange puts the previous properties back; a paragraph mark that goes away joins the paragraph to the next one; rows are kept or removed. Move range markers go with "all".
Delete commentsThe w:comment (and its replies), the range markers and reference runs in every story, and the entries in commentsExtended, commentsIds and commentsExtensible.
Remove hidden textRuns whose effective w:vanish is on; paragraphs left with only hidden content and a hidden mark.
Unhide sheets, edit cells (Excel)state is removed. A cell gets <v> for a number, t="b" for TRUE/FALSE, an inline string for text, or <f> for a formula (its cached value goes, calcChain.xml is removed and fullCalcOnLoad set so Excel recalculates); a shared formula's other cells get their formulas written out first.
Remove protection, external links, connections, namesworkbookProtection, fileSharing and sheetProtection elements; an external link's part and relationship, formulas that used it losing their formula (keeping the cached value) and the others renumbered; connections with the query tables that use them.
PowerPointClearing formatting removes the run's a:rPr attributes and children but lang, altLang, spelling state, links; paragraph a:pPr keeps lvl. Deleting a slide removes it from sldIdLst, sections and custom shows, its relationship, its notes and comments, and links to it from other slides; deleting a shape drops relationships (and parts) nothing else uses.
Remove macrosvbaProject.bin with vbaData.xml, key-map customizations and attached toolbars (parts, relationships, Overrides), XLM macro sheets with the names that point into them, and the main part's content type becomes the macro-free one.
Remove personal informationcreator, lastModifiedBy, lastPrinted (core), Company, Manager, HyperlinkBase and a Template with a path (app); optionally the custom properties part and the authors of comments and changes (they become "Author").
PartsEdit any XML part as text (checked for well-formedness before it applies), replace a part's bytes with a file, remove a part (with the relationships to it and its Override).

What the tool shows, and its limits

The libraries

ES modules in lib/office/, without user interface; they work in a page, a worker and jsc (where they use lib/compression/inflate.js when there is no DecompressionStream).

ModuleAPI
office-file.jsawait OfficeFile.open(bytesOrBlob) → { package, kind, document } (throws with code "compound-file", "opendocument", "not-ooxml", "not-zip"); file.vba(), file.vbaParts(), file.removeMacros(), file.refresh(), await file.save().
office-package.jsOfficePackage: parts, part(name), contentType(name), contentTypes, relationships(source), allRelationships(), relationshipsTo(name), relationship(source, id), resolve(source, target), mainPart, kind, properties(), bytes/text/xml/tryXml(name); editing inside change(label, fn): modify(name) (the tree to change), writePart, deletePart, addRelationship, removeRelationship, setContentType, removeProperties(options), removeMacros(); undo(), dirty, changedParts(), currentBytes(name), await save(), suggestedName(fileName).
word-document.jsnew WordDocument(pkg): stories, body, paragraphs (style, direct, mark, runs, numbering, table, section), sections, fields, hyperlinks, bookmarks, contentControls, drawings, trackedChanges, comments, notes, settings; paragraphFormatting(p), runFormatting(run), markFormatting(p), styleUsage(), isHidden(run); edits clearDirectFormatting(paragraphs | "all", options), clearRunFormatting(run), removeDirectProperty(target, local, attributes), setParagraphStyle, setRunText, deleteParagraph, deleteRun, acceptChange/rejectChange/acceptAll/rejectAll, deleteComment/deleteAllComments, removeHiddenText(), removeAttachedTemplate().
word-styles.jsWordStyles (list, get, chain, defaultStyle, docDefaults, latent, themeFonts), WordNumbering (abstracts, instances, level, label, formatNumber), WordFormatting.resolve(levels, WordFormatting.PARAGRAPH | RUN, themeFonts).
workbook.jsnew Workbook(pkg): sheets, definedNames, properties, sharedStrings, styles, cellFormat(index), externalLinks, connections, pivotCaches, worksheet(sheet) (cells, merged, hyperlinks, validations, conditional formats, protection, tables, comments, drawings, pivot and query tables, controls); edits setSheetState, setCell, removeProtection, removeExternalLink/removeAllExternalLinks, removeConnection/removeAllConnections, deleteDefinedName, removeMacros(); helpers Workbook.shiftFormula, columnName, parseAddress, isDateFormat, dateFromSerial.
presentation.jsnew Presentation(pkg): slides (shapes, notes, comments, links, media, layout, master), layouts, masters, sections, links, properties; paragraphFormatting, runFormatting, textLevels; edits clearDirectFormatting, removeDirectProperty, setRunText, setSlideHidden, deleteSlide, deleteShape, deleteNotes, deleteComments.
office-review.jsOfficeReview.review(file) → [{ severity, category, title, detail, parts, where }].
compound-file.js, vba-project.js, ole-object.jsCompoundFile.parse(bytes) (entries, get, read, describe); VbaProject.parse(bytes) (modules with source, references, protection), VbaProject.scan(source), VbaProject.decompress; OleObject.describe(bytes) (class, ProgID, link moniker, OLE Package file).
ooxml.jsOoxml: lookups by local name (child, children, descendants, attribute, relationshipId, references), isOn, content type names, units.
const file = await OfficeFile.open(bytes);
const doc = file.document;                                   // a WordDocument for a .docx
const heading = doc.paragraphs[0];
doc.paragraphFormatting(heading);                            // [{ label: "space before", value: "0 pt", source: "direct", overridden: [...] }, …]
doc.clearDirectFormatting([heading]);                        // one undo step
doc.setParagraphStyle([heading], "Heading1");
const saved = await file.save();                             // unchanged parts copied byte for byte