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 trails.
  • Дедуплікація — автор + заголовок + дата створення — дешевий, але ефективний fingerprint.
  • Чистка PII — прочитайте core properties перед публікацією, потім використайте EditableDocument, щоб їх обнулити.

Дивіться також