Skip to content

Извлечение метаданных документа

В каждый Office-формат встроен небольшой набор «core properties» — автор, дата последней модификации, заголовок, тема, ключевые слова — плюс дополнительный набор для каждого формата. Office Oxide отдаёт оба.

Формат и базовая информация

Handle Document сообщает имя формата и счётчики (листы, слайды, секции):

Python

from office_oxide import Document

with Document.open("report.docx") as doc:
    print(doc.format)            # "docx"
    print(doc.detect_format())   # подтверждение через magic bytes

Rust

use office_oxide::{Document, DocumentFormat};

let doc = Document::open("report.docx")?;
assert_eq!(doc.format(), DocumentFormat::Docx);

JavaScript

using doc = Document.open('report.docx');
console.log(doc.format);        // "docx"

Go

doc, err := officeoxide.Open("report.docx")
if err != nil { log.Fatal(err) }
defer doc.Close()

fmtName, _ := doc.Format()   // "docx"
fmt.Println(fmtName)

C#

using OfficeOxide;

using var doc = Document.Open("report.docx");
Console.WriteLine(doc.Format);   // "docx"

Core properties

Для OOXML core properties лежат в docProps/core.xml. Уходите в формат-специфичный аксессор:

Python

from office_oxide import Document

with Document.open("report.docx") as doc:
    docx = doc.as_docx()
    props = docx.core_properties()
    print(props.title)            # str | None
    print(props.author)           # str | None
    print(props.created)          # datetime | None
    print(props.modified)         # datetime | None
    print(props.subject)          # str | None
    print(props.keywords)         # str | None

Rust

use office_oxide::Document;

let doc = Document::open("report.docx")?;
if let Some(docx) = doc.as_docx() {
    let props = docx.core_properties();
    println!("{:?}", props.title);
    println!("{:?}", props.author);
}

Тот же core_properties() есть на as_xlsx() и as_pptx().

Go

В Go core properties доступны через унифицированный JSON IR:

doc, _ := officeoxide.Open("report.docx")
defer doc.Close()

irJSON, _ := doc.ToIRJSON()
var ir struct {
    Metadata struct {
        Title    string `json:"title"`
        Author   string `json:"author"`
        Created  string `json:"created"`
        Modified string `json:"modified"`
        Subject  string `json:"subject"`
        Keywords string `json:"keywords"`
    } `json:"metadata"`
}
json.Unmarshal([]byte(irJSON), &ir)
fmt.Println(ir.Metadata.Title, ir.Metadata.Author)

C#

using OfficeOxide;
using System.Text.Json;

using var doc = Document.Open("report.docx");
using var ir = JsonDocument.Parse(doc.ToIrJson());

var meta = ir.RootElement.GetProperty("metadata");
Console.WriteLine(meta.GetProperty("title").GetString());
Console.WriteLine(meta.GetProperty("author").GetString());
Console.WriteLine(meta.GetProperty("created").GetString());

Расширенные (app) properties

docProps/app.xml хранит расширенные метаданные: страницы, слова, абзацы, слайды, имя и версия приложения, гиперссылки и т. д.

Python

with Document.open("report.docx") as doc:
    app = doc.as_docx().app_properties()
    print(app.application)   # "Microsoft Office Word"
    print(app.app_version)
    print(app.pages)
    print(app.words)
    print(app.paragraphs)

Для PPTX app_properties() выставляет slides, notes, presentation_format и т. д.; для XLSX — список имён листов.

Пользовательские properties

core_properties() и app_properties() покрывают стандартные наборы. Для приложений с собственными ключами (заданными в «Свойствах документа → Дополнительные свойства» Word) используйте:

with Document.open("report.docx") as doc:
    custom = doc.as_docx().custom_properties()
    for name, value in custom.items():
        print(name, value)

Legacy-форматы

DOC, XLS и PPT хранят метаданные в OLE2-стримах \005SummaryInformation и \005DocumentSummaryInformation. Office Oxide парсит их в ту же форму core_properties():

with Document.open("legacy.doc") as doc:
    props = doc.as_doc().core_properties()
    print(props.author, props.created)

Зачем это нужно

  • Индексация поиска — заголовок, автор и ключевые слова двигают document discovery.
  • Compliance — last-modified, автор и история ревизий идут в audit trail.
  • Дедупликация — author + title + created date — дешёвый, но рабочий fingerprint.
  • Чистка PII — прочитайте core properties перед публикацией, затем используйте EditableDocument, чтобы их обнулить.

Смотрите также