Skip to content

Извлечение текста из Office-документов

Office Oxide предоставляет единственную точку входа — extract_text() (или Document.open(...).plain_text()) — которая одинаково работает для DOCX, XLSX, PPTX, DOC, XLS и PPT. Никакой форматно-зависимой логики.

Одноразовый вызов

Самый быстрый вариант: один вызов открывает файл, запускает нужный экстрактор и возвращает строку.

Rust

use office_oxide::extract_text;

let text = extract_text("report.docx")?;
println!("{text}");

Python

import office_oxide

text = office_oxide.extract_text("report.docx")
print(text)

JavaScript

import { extractText } from 'office-oxide';

console.log(extractText('report.docx'));

Go

import officeoxide "github.com/yfedoseev/office_oxide/go"

text, err := officeoxide.ExtractText("report.docx")

C#

using OfficeOxide;

string text = OfficeOxide.ExtractText("report.docx");

C

int err = 0;
char *text = office_extract_text("report.docx", &err);
if (text) {
    printf("%s\n", text);
    office_oxide_free_string(text);
}

Переиспользуемый handle

Если помимо текста нужны другие форматы вывода (Markdown, HTML, IR) — откройте документ один раз и переиспользуйте handle:

Rust

use office_oxide::Document;

let doc = Document::open("report.docx")?;
let text = doc.plain_text();
let md   = doc.to_markdown();

Python

from office_oxide import Document

with Document.open("report.docx") as doc:
    text = doc.plain_text()
    md   = doc.to_markdown()

JavaScript

import { Document } from 'office-oxide';

using doc = Document.open('report.docx');
const text = doc.plainText();
const md   = doc.toMarkdown();

C

int err = 0;
OfficeDocumentHandle *doc = office_document_open("report.docx", &err);
if (!doc) { fprintf(stderr, "open failed: code=%d\n", err); return 1; }

char *text = office_document_plain_text(doc, &err);
char *md   = office_document_to_markdown(doc, &err);
/* use text / md ... */
office_oxide_free_string(text);
office_oxide_free_string(md);
office_document_free(doc);

Что получаете для каждого формата

Формат Вывод
DOCX Текст body в порядке документа + колонтитулы; мягкие переносы удаляются
XLSX Значения ячеек по всем листам; в строке — через табуляцию, между листами — пустая строка
PPTX Заголовок слайда, body-плейсхолдеры, ячейки таблиц и заметки — один абзацный блок на слайд
DOC Та же структура, что и DOCX — парсится прямо из piece-table CFB
XLS Та же структура, что и XLSX — парсится прямо из записей BIFF8
PPT Та же структура, что и PPTX — парсится из потока PowerPoint Document

Из байтов (без временного файла)

Удобно для serverless- и стриминговых пайплайнов.

Rust

use std::io::Cursor;
use office_oxide::{Document, DocumentFormat};

let data = std::fs::read("report.docx")?;
let doc = Document::from_reader(Cursor::new(data), DocumentFormat::Docx)?;
let text = doc.plain_text();

Python

import requests
from office_oxide import Document

data = requests.get("https://example.com/report.docx").content
with Document.from_bytes(data, "docx") as doc:
    print(doc.plain_text())

JavaScript

import { Document } from 'office-oxide';

const res = await fetch('https://example.com/report.docx');
const data = new Uint8Array(await res.arrayBuffer());
using doc = Document.fromBytes(data, 'docx');
console.log(doc.plainText());

C

/* format must be one of: "docx" "xlsx" "pptx" "doc" "xls" "ppt" (lowercase) */
int err = 0;
OfficeDocumentHandle *doc =
    office_document_open_from_bytes(data, len, "docx", &err);
if (doc) {
    char *text = office_document_plain_text(doc, &err);
    if (text) { printf("%s\n", text); office_oxide_free_string(text); }
    office_document_free(doc);
}

WASM

import { WasmDocument } from 'office-oxide-wasm';

const res = await fetch('https://example.com/report.docx');
const data = new Uint8Array(await res.arrayBuffer());
using doc = new WasmDocument(data, 'docx');
console.log(doc.plainText());

Производительность

Формат Среднее p99 Успешность
DOCX (2 538 файлов) 0,8 мс 3,9 мс 98,9%
XLSX (1 802 файла) 5,0 мс 40 мс 97,8%
PPTX (806 файлов) 0,7 мс 3,9 мс 98,4%
DOC (246 файлов) 0,3 мс 3,4 мс 94,7%
XLS (494 файла) 2,8 мс 75 мс 99,2%
PPT (176 файлов) 0,7 мс 6,6 мс 100%

Полная методология бенчмарков — Производительность.

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