Application vnd openxmlformats officedocument wordprocessingml document
Internet Media Types [1] — типы данных, которые могут быть переданы посредством сети интернет с применением стандарта MIME. Ниже приведён список MIME-заголовков и расширений файлов.
Содержание
Общие типы [ править | править код ]
Согласно RFC 2045, RFC 2046, RFC 4288, RFC 4289 и RFC 4855 [2] выделяются следующие базовые типы передаваемых данных:
Внутренний формат прикладной программы
audio [ править | править код ]
image [ править | править код ]
message [ править | править код ]
model [ править | править код ]
multipart [ править | править код ]
text [ править | править код ]
video [ править | править код ]
vnd [ править | править код ]
x [ править | править код ]
x-pkcs [ править | править код ]
The Office Open XML file formats are a set of file formats that can be used to represent electronic office documents. There are formats for word processing documents, spreadsheets and presentations as well as specific formats for material such as mathematical formulae, graphics, bibliographies etc.
The formats were developed by Microsoft and first appeared in Microsoft Office 2007. They were standardized between December 2006 and November 2008, first by the Ecma International consortium, where they became ECMA-376, and subsequently, after a contentious standardization process, by the ISO/IEC’s Joint Technical Committee 1, where they became ISO/IEC 29500:2008.
Contents
Container [ edit ]
Office Open XML documents are stored in Open Packaging Convention (OPC) packages, which are ZIP files containing XML and other data files, along with a specification of the relationships between them. [2] Depending on the type of the document, the packages have different internal directory structures and names. An application will use the relationships files to locate individual sections (files), with each having accompanying metadata, in particular MIME metadata.
[Content_Types].xml This file provided MIME type information for parts of the package, using defaults for certain file extensions and overrides for parts specified by IRI. _rels This directory contains relationships for the files within the package. To find the relationships for a specific file, look for the _rels directory that is a sibling of the file, and then for a file that has the original file name with a .rels appended to it. For example, if the content types file had any relationships, there would be a file called [Content_Types].xml.rels inside the _rels directory. _rels/.rels This file is where the package relationships are located. Applications look here first. Viewing in a text editor, one will see it outlines each relationship for that section. In a minimal document containing only the basic document.xml file, the relationships detailed are metadata and document.xml. docProps/core.xml This file contains the core properties for any Office Open XML document. word/document.xml This file is the main part for any Word document.
Relationships [ edit ]
An example relationship file (word/_rels/document.xml.rels), is:
The following code shows an example of inline markup for a hyperlink:
In this example, the Uniform Resource Locator (URL) is in the Target attribute of the Relationship referenced through the relationship Id, «rId2» in this case. Linked images, templates, and other items are referenced in the same way.
Pictures can be embedded or linked using a tag:
This is the reference to the image file. All references are managed via relationships. For example, a document.xml has a relationship to the image. There is a _rels directory in the same directory as document.xml, inside _rels is a file called document.xml.rels. In this file there will be a relationship definition that contains type, ID and location. The ID is the referenced ID used in the XML document. The type will be a reference schema definition for the media type and the location will be an internal location within the ZIP package or an external location defined with a URL.
Document properties [ edit ]
Office Open XML uses the Dublin Core Metadata Element Set and DCMI Metadata Terms to store document properties. Dublin Core is a standard for cross-domain information resource description and is defined in ISO 15836:2003.
An example document properties file (docProps/core.xml) that uses Dublin Core metadata, is:
Document markup languages [ edit ]
An Office Open XML file may contain several documents encoded in specialized markup languages corresponding to applications within the Microsoft Office product line. Office Open XML defines multiple vocabularies using 27 namespaces and 89 schema modules.
The primary markup languages are:
Shared markup language materials include:
In addition to the above markup languages custom XML schemas can be used to extend Office Open XML.
Design approach [ edit ]
Patrick Durusau, the editor of ODF, has viewed the markup style of OOXML and ODF as representing two sides of a debate: the «element side» and the «attribute side». He notes that OOXML represents «the element side of this approach» and singles out the KeepNext element as an example:
The XML Schema of Office Open XML emphasizes reducing load time and improving parsing speed. [4] In a test with applications current in April 2007, XML-based office documents were slower to load than binary formats. [5] To enhance performance, Office Open XML uses very short element names for common elements and spreadsheets save dates as index numbers (starting from 1900 or from 1904). [6] In order to be systematic and generic, Office Open XML typically uses separate child elements for data and metadata (element names ending in Pr for properties) rather than using multiple attributes, which allows structured properties. Office Open XML does not use mixed content but uses elements to put a series of text runs (element name r) into paragraphs (element name p). The result is terse [ citation needed ] and highly nested in contrast to HTML, for example, which is fairly flat, designed for humans to write in text editors and is more congenial for humans to read.
The naming of elements and attributes within the text has attracted some criticism. There are three different syntaxes in OOXML (ECMA-376) for specifying the color and alignment of text depending on whether the document is a text, spreadsheet, or presentation. Rob Weir (an IBM employee and co-chair of the OASIS OpenDocument Format TC) asks «What is the engineering justification for this horror?». He contrasts with OpenDocument: «ODF uses the W3C’s XSL-FO vocabulary for text styling, and uses this vocabulary consistently». [7]
Some have argued the design is based too closely on Microsoft applications. In August 2007, the Linux Foundation published a blog post calling upon ISO National Bodies to vote «No, with comments» during the International Standardization of OOXML. It sa >[8]
The version of the standard submitted to JTC 1 was 6546 pages long. The need and appropriateness of such length has been questioned. [9] [10] Google stated that «the ODF standard, which achieves the same goal, is only 867 pages» [9]
WordprocessingML (WML) [ edit ]
Word processing documents use the XML vocabulary known as WordprocessingML normatively defined by the schema wml.xsd which accompanies the standard. This vocabulary is defined in clause 11 of Part 1. [11]
SpreadsheetML (SML) [ edit ]
Spreadsheet documents use the XML vocabulary known as SpreadsheetML normatively defined by the schema sml.xsd which accompanies the standard. This vocabulary is described in clause 12 of Part 1. [11]
The representation of date and time values in SpreadsheetML has attracted some criticism. ECMA-376 1st edition does not conform to ISO 8601:2004 «Representation of Dates and Times». It requires that implementations replicate a Lotus 1-2-3 [12] bug that erroneously treats 1900 as a leap year. Products complying with ECMA-376 would be required to use the WEEKDAY() spreadsheet function, and therefore assign incorrect dates to some days of the week, and also miscalculate the number of days between certain dates. [13] ECMA-376 2nd edition (ISO/IEC 29500) allows the use of 8601:2004 «Representation of Dates and Times» in addition to the Lotus 1-2-3 bug-compatible form. [14] [15]
Office MathML (OMML) [ edit ]
Office Math Markup Language is a mathematical markup language which can be embedded in WordprocessingML, with intrinsic support for including word processing markup like revision markings, [16] footnotes, comments, images and elaborate formatting and styles. [17] The OMML format is different from the World W >[18] through XSL Transformations; tools are prov >[19]
The following Office MathML example defines the fraction: π 2 >>
Some have queried the need for Office MathML (OMML) instead advocating the use of MathML, a W3C recommendation for the «inclusion of mathematical expressions in Web pages» and «machine to machine communication». [20] Murray Sargent has answered some of these issues in a blog post, which details some of the philosophical differences between the two formats. [21]
DrawingML [ edit ]
DrawingML is the vector graphics markup language used in Office Open XML documents. Its major features are the graphics rendering of text elements, graphical vector-based shape elements, graphical tables and charts.
The DrawingML table is the third table model in Office Open XML (next to the table models in WordprocessingML and SpreadsheetML) and is optimized for graphical effects and its main use is in presentations created with PresentationML markup. DrawingML contains graphics effects (like shadows and reflection) that can be used on the different graphical elements that are used in DrawingML. In DrawingML you can also create 3d effects, for instance to show the different graphical elements through a flexible camera viewpoint. It is possible to create separate DrawingML theme parts in an Office Open XML package. These themes can then be applied to graphical elements throughout the Office Open XML package. [22]
DrawingML is unrelated to the other vector graphics formats such as SVG. These can be converted to DrawingML to include natively in an Office Open XML document. This is a different approach to that of the OpenDocument format, which uses a subset of SVG, and includes vector graphics as separate files.
A DrawingML graphic’s dimensions are specified in English Metric Units (EMUs). It is so called because it allows an exact common representation of dimensions originally in either English or Metric units. This unit is defined as 1/360,000 of a centimeter and thus there are 914,400 EMUs per inch, and 12,700 EMUs per point. This unit was chosen so that integers can be used to accurately represent most dimensions encountered in a document. Floating point cannot accurately represent a fraction that is not a sum of powers of two and the error is magnified when the fractions are added together many times, resulting in misalignment. As an inch is exactly 2.54 centimeters, or 127/50, 1/127 inch is an integer multiple of a power-of-ten fraction of the meter (2×10 −4 m). To accurately represent (with an integer) 1 μm = 10 −6 m, a divisor of 100 is further needed. To accurately represent the point unit, a divisor of 72 is needed, which also allows divisions by 2, 3, 4, 6, 8, 9, 12, 18, 24, and 36 to be accurate. Multiplying these together gives 127×72×100 = 914,400 units per inch; this also allows exact representations of multiples of 1/100 & 1/32 inch. According to Rick Jelliffe, programmer and standards activist (ISO, W3C, IETF), EMUs are a rational solution to a particular set of design criteria. [23]
Some have criticised the use of DrawingML (and the transitional-use-only VML) instead of W3C recommendation SVG. [24] VML d >[25]
Foreign resources [ edit ]
Non-XML content [ edit ]
OOXML documents are typically composed of other resources in addition to XML content (graphics, video, etc.).
Some have criticised the choice of permitted format for such resources: ECMA-376 1st edition specifies «Embedded Object Alternate Image Requests Types» and «Clipboard Format Types», which refer to Windows Metafiles or Enhanced Metafiles – each of which are proprietary formats that have hard-coded dependencies on Windows itself. The critics state the standard should instead have referenced the platform neutral standard ISO/IEC 8632 «Computer Graphics Metafile». [13]
Foreign markup [ edit ]
The Standard provides three mechanisms to allow foreign markup to be embedded within content for editing purposes:
These are defined in clause 17.5 of Part 1.
Compatibility settings [ edit ]
Versions of Office Open XML contain what are termed «compatibility settings». These are contained in Part 4 («Markup Language Reference») of ECMA-376 1st Edition, but during standardization were moved to become a new part (also called Part 4) of ISO/IEC 29500:2008 («Transitional Migration Features»).
These settings (including element with names such as autoSpaceLikeWord95, footnoteLayoutLikeWW8, lineWrapLikeWord6, mwSmallCaps, shapeLayoutLikeWW8, suppressTopSpacingWP, truncateFontHeightsLikeWP6, uiCompat97To2003, useWord2002TableStyleRules, useWord97LineBreakRules, wpJustification and wpSpaceW >[26] As a result, new text was added to ISO/IEC 29500 to document them. [27]
An article in Free Software Magazine has criticized the markup used for these settings. Office Open XML uses distinctly named elements for each compatibility setting, each of which is declared in the schema. The repertoire of settings is thus limited — for new compatibility settings to be added, new elements may need to be declared, «potentially creating thousands of them, each having nothing to do with interoperability». [28]
Extensibility [ edit ]
The standard provides two types of extensibility mechanism, Markup Compatibility and Extensibility (MCE) defined in Part 3 (ISO/IEC 29500-3:2008) and Extension Lists defined in clause 18.2.10 of Part 1.
For older *.doc documents this was enough:
What mime type should I use for new docx documents? Also for pptx and xlsx documents?
8 Answers 8
Here are the correct Microsoft Office MIME types for HTTP content streaming:
For further details check out this TechNet article and this blog post.
Here is a (almost) complete all of file extensions’s MIME in a JSON format. Just do example: MIME[«ppt»], MIME[«docx»], etc
This post will explore various approaches of fetching MIME Type across various programming languages with their CONS in one-line description as header. So, use them accordingly and the one which works for you.
Using python-magic
Using built-in mimeypes module — Map filenames to MimeTypes modules
Operating System dependent
It will use FileTypeDetector implementations to probe the MIME type and invokes the probeContentType of each implementation to resolve the type. Hence, if the file is known to the implementations then the content type is returned. However, if that doesn’t happen, a system-default file type detector is invoked.
Resolve using first few characters of the input stream
Using built-in table of MIME types
It returns the matrix of MIME types used by all instances of URLConnection which then is used to resolve the input file type. However, this matrix of MIME types is very limited when it comes to URLConnection.
By default, the class uses content-types.properties file in JRE_HOME/lib. We can, however, extend it, by specifying a user-specific table using the content.types.user.table property:
Interpret the Magic Number fetched using FileReader API
Final result looks something like this when one use javaScript to fetch the MimeType based on filestream. Open the embedded jsFiddle to see and understand this approach.
Bonus: It’s accessible for most of the MIME Types and also you can add custom Mime Types in the getMimetype function. Also, it has FULL SUPPORT for MS Office Files Mime Types.
The steps to calculate mime type for a file in this example would be:
Browser Support (Above 95% overall and Close to 100% in all modern browsers):
Структура документа WordprocessingML (Open XML SDK)
В этом разделе обсуждается базовая структура документа WordprocessingML и рассматриваются важные классы пакета Open XML SDK, чаще всего используемые для создания документов WordprocessingML.
В этом разделе:
Важные части WordprocessingML
API Open XML SDK 2.5 предоставляет строго типизированные классы в пространстве имен DocumentFormat.OpenXML.WordprocessingML, соответствующие элементам WordprocessingML.
В следующей таблице перечисляются некоторые важные элементы WordprocessingML, часть пакета документа WordprocessingML, к которой относится элемент (если применимо), и управляемый класс, который представляет элемент в программном интерфейсе Пакет SDK 2.5 Open XML.
| Часть пакета | Элемент WordprocessingML | Класс Пакет SDK 2.5 Open XML | Описание |
|---|---|---|---|
| Основной документ | document | Document | Корневой элемент основной части документа. |
| Комментарии | комментарии | Comments | Корневой элемент для части комментариев. |
| Параметры документа | settings | Settings | Корневой элемент для части параметров документа. |
| Концевые сноски | endnotes | Endnotes | Корневой элемент для части концевых сносок. |
| Нижний колонтитул | ftr | Footer | Корневой элемент для части нижнего колонтитула. |
| Сноски | footnotes | Footnotes | Корневой элемент для части сносок. |
| Документ глоссария | glossaryDocument | GlossaryDocument | Корневой элемент для части документа глоссария. |
| Заголовок | hdr | Header | Корневой элемент для части верхнего колонтитула. |
| Определения стилей | styles | Styles | Корневой элемент для части определения стилей. |
Простейший случай документа
Документ WordprocessingML организован в виде статей. Статья это область содержимого в документе WordprocessingML. В WordprocessingML имеются следующие статьи:
Как я разбирал docx с помощью XSLT
Задача обработки документов в формате docx, а также таблиц xlsx и презентаций pptx является весьма нетривиальной. В этой статье расскажу как научиться парсить, создавать и обрабатывать такие документы используя только XSLT и ZIP архиватор.
Зачем?
docx — самый популярный формат документов, поэтому задача отдавать информацию пользователю в этом формате всегда может возникнуть. Один из вариантов решения этой проблемы — использование готовой библиотеки, может не подходить по ряду причин:
Поэтому в этой статье будем использовать только самые базовые инструменты для работы с docx документом.
Структура docx
Для начала разоберёмся с тем, что собой представляет docx документ. docx это zip архив который физически содержит 2 типа файлов:
А логически — 3 вида элементов:
Они подробно описаны в стандарте ECMA-376: Office Open XML File Formats, основная часть которого — PDF документ на 5000 страниц, и ещё 2000 страниц бонусного контента.
Минимальный docx
Простейший docx после распаковки выглядит следующим образом
Давайте посмотрим из чего он состоит.
[Content_Types].xml
Находится в корне документа и перечисляет MIME типы содержимого документа:
_rels/.rels
Главный список связей документа. В данном случае определена всего одна связь — сопоставление с идентификатором rId1 и файлом word/document.xml — основным телом документа.
word/document.xml
word/_rels/document.xml.rels
Даже если связей нет, этот файл должен существовать.
docx и Microsoft Word
docx созданный с помощью Microsoft Word, да в принципе и с помощью любого другого редактора имеет несколько дополнительных файлов.
Вот что в них содержится:
В сложных документах частей может быть гораздо больше.
Реверс-инжиниринг docx
Итак, первоначальная задача — узнать как какой-либо фрагмент документа хранится в xml, чтобы потом создавать (или парсить) подобные документы самостоятельно. Для этого нам понадобятся:
Инструменты
Также понадобятся скрипты для автоматического (раз)архивирования и форматирования XML.
Использование под Windows:
Использование
Поиск изменений происходит следующим образом:
Пример 1. Выделение текста жирным
Посмотрим на практике, как найти тег который определяет форматирование текста жирным шрифтом.
Рассмотрим его подробно:
docProps/app.xml
Изменение времени нам не нужно.
docProps/core.xml
Изменение версии документа и даты модификации нас также не интересует.
word/document.xml
Изменения в w:rsidR не интересны — это внутренняя информация для Microsoft Word. Ключевое изменение тут
в параграфе с Test. Видимо элемент и делает текст жирным. Оставляем это изменение и отменяем остальные.
word/settings.xml
Также не содержит ничего относящегося к жирному тексту. Отменяем.
7 Запаковываем папку с 1м изменением (добавлением ) и проверяем что документ открывается и показывает то, что ожидалось.
8 Коммитим изменение.
Пример 2. Нижний колонтитул
Теперь разберём пример посложнее — добавление нижнего колонтитула.
Вот первоначальный коммит. Добавляем нижний колонтитул с текстом 123 и распаковываем документ. Такой diff получается первоначально:
Сразу же исключаем изменения в docProps/app.xml и docProps/core.xml — там тоже самое, что и в первом примере.
[Content_Types].xml
footer явно выглядит как то, что нам нужно, но что делать с footnotes и endnotes? Являются ли они обязательными при добавлении нижнего колонтитула или их создали заодно? Ответить на этот вопрос не всегда просто, вот основные пути:

Идём пока что дальше.
word/_rels/document.xml.rels
Изначально diff выглядит вот так:
Видно, что часть изменений связана с тем, что Word изменил порядок связей, уберём их:
Опять появляются footer, footnotes, endnotes. Все они связаны с основным документом, перейдём к нему:
word/document.xml
Редкий случай когда есть только нужные изменения. Видна явная ссылка на footer из sectPr. А так как ссылок в документе на footnotes и endnotes нет, то можно предположить что они нам не понадобятся.
word/settings.xml
А вот и появились ссылки на footnotes, endnotes добавляющие их в документ.
word/styles.xml
Изменения в стилях нас интересуют только если мы ищем как поменять стиль. В данном случае это изменение можно убрать.
word/footer1.xml
Посмотрим теперь собственно на сам нижний колонтитул (часть пространств имён опущена для читабельности, но в документе они должны быть):
В результате анализа всех изменений делаем следующие предположения:
Уменьшаем diff до этого набора изменений:
Затем запаковываем документ и открываем его.
Если всё сделано правильно, то документ откроется и в нём будет нижний колонтитул с текстом 123. А вот и итоговый коммит.
Таким образом процесс поиска изменений сводится к поиску минимального набора изменений, достаточного для достижения заданного результата.
Практика
Найдя интересующее нас изменение, логично перейти к следующему этапу, это может быть что-либо из:
Тут нам потребуются знания XSLT и XPath.
Давайте напишем достаточно простое преобразование — замену или добавление нижнего колонтитула в существующий документ. Писать я буду на языке Caché ObjectScript, но даже если вы его не знаете — не беда. В основном будем вызовать XSLT и архиватор. Ничего более. Итак, приступим.
Алгоритм
Алгоритм выглядит следующим образом:
Распаковка
Создаём файл нижнего колонтитула
На вход поступает текст нижнего колонтитула, запишем его в файл in.xml:
В XSLT (файл — footer.xsl) будем создавать нижний колонтитул с текстом из тега xml (часть пространств имён опущена, вот полный список):
В результате получится файл нижнего колонтитула footer0.xml :
Добавляем ссылку на колонтитул в список связей основного документа
Сссылки с идентификатором rId0 как правило не существует. Впрочем можно использовать XPath для получения идентификатора которого точно не существует.
Добавляем ссылку на footer0.xml c идентификатором rId0 в word/_rels/document.xml.rels :
Прописываем ссылки в документе
Далее надо в каждый тег добавить тег или заменить в нём ссылку на наш нижний колонтитул. Оказалось, что у каждого тега может быть 3 тега — для первой страницы, четных страниц и всего остального:
Добавляем колонтитул в [Content_Types].xml
Добавляем в [Content_Types].xml информацию о том, что /word/footer0.xml имеет тип application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml :
В результате
Весь код опубликован. Работает он так:
Выводы
Используя только XSLT и ZIP можно успешно работать с документами docx, таблицами xlsx и презентациями pptx.








