표 추출
Office Oxide는 표를 IR의 일급 요소로 취급합니다. DOCX의 모든 <w:tbl>, XLSX의 모든 범위, PPTX의 모든 <a:tbl>은 타입이 지정된 Table { rows: [[cell, ...]] } 형태로 반환됩니다. 루프 하나로 세 가지 형식을 모두 처리할 수 있습니다.
문서의 모든 표 순회하기
Rust
use office_oxide::Document;
use office_oxide::ir::Element;
let doc = Document::open("report.docx")?;
let ir = doc.to_ir();
for section in &ir.sections {
for el in §ion.elements {
if let Element::Table(t) = el {
for row in &t.rows {
println!("{row:?}");
}
}
}
}
Python
from office_oxide import Document
with Document.open("report.docx") as doc:
ir = doc.to_ir()
for section in ir["sections"]:
for el in section["elements"]:
if el["kind"] == "Table":
for row in el["rows"]:
print(row)
JavaScript
using doc = Document.open('report.docx');
const ir = doc.toIr();
for (const section of ir.sections) {
for (const el of section.elements) {
if (el.kind === 'Table') {
for (const row of el.rows) {
console.log(row);
}
}
}
}
Go
doc, err := officeoxide.Open("report.docx")
if err != nil { log.Fatal(err) }
defer doc.Close()
irJSON, _ := doc.ToIRJSON()
var ir struct {
Sections []struct {
Elements []struct {
Kind string `json:"kind"`
Rows [][]string `json:"rows"`
} `json:"elements"`
} `json:"sections"`
}
json.Unmarshal([]byte(irJSON), &ir)
for _, section := range ir.Sections {
for _, el := range section.Elements {
if el.Kind == "Table" {
for _, row := range el.Rows {
fmt.Println(row)
}
}
}
}
C#
using OfficeOxide;
using System.Text.Json;
using var doc = Document.Open("report.docx");
using var ir = JsonDocument.Parse(doc.ToIrJson());
foreach (var section in ir.RootElement.GetProperty("sections").EnumerateArray())
{
foreach (var el in section.GetProperty("elements").EnumerateArray())
{
if (el.GetProperty("kind").GetString() != "Table") continue;
foreach (var row in el.GetProperty("rows").EnumerateArray())
{
Console.WriteLine(string.Join(" | ", row.EnumerateArray().Select(c => c.GetString())));
}
}
}
C
int err = 0;
OfficeDocumentHandle *doc = office_document_open("report.docx", &err);
char *ir_json = office_document_to_ir_json(doc, &err); /* DocumentIR as JSON */
if (ir_json) {
/* parse ir_json with your JSON lib, then walk sections -> elements,
keeping every element whose "kind" == "Table" and iterating its "rows" */
office_oxide_free_string(ir_json);
}
office_document_free(doc);
WASM
import { WasmDocument } from 'office-oxide-wasm';
const data = new Uint8Array(await (await fetch('/report.docx')).arrayBuffer());
const doc = new WasmDocument(data, 'docx');
try {
const ir = doc.toIr(); // JS object, schema == Rust DocumentIR
for (const section of ir.sections) {
for (const el of section.elements) {
if (el.kind === 'Table') {
for (const row of el.rows) {
console.log(row);
}
}
}
}
} finally {
doc.free();
}
XLSX: 시트 범위마다 표 하나씩
스프레드시트에서는 각 섹션이 워크시트에 대응하고, 표는 감지된 사용 범위에 매핑됩니다. 빈 셀은 빈 문자열로 출력되고, 병합 셀은 왼쪽 위 값으로 펼쳐지며 나머지는 빈 칸이 됩니다.
Python
import csv
from office_oxide import Document
with Document.open("budget.xlsx") as doc:
ir = doc.to_ir()
for section in ir["sections"]:
sheet_name = section.get("title", "Sheet")
out_path = f"{sheet_name}.csv"
with open(out_path, "w", newline="") as f:
w = csv.writer(f)
for el in section["elements"]:
if el["kind"] == "Table":
for row in el["rows"]:
w.writerow(row)
수식, 병합 셀, 이름이 지정된 범위 등 세밀한 셀 접근이 필요하다면 형식별 API를 사용하세요:
Python
with Document.open("budget.xlsx") as doc:
xlsx = doc.as_xlsx()
for sheet in xlsx.sheets():
print(sheet.name(), sheet.dimensions())
DOCX: 단락과 섞여 있는 표
IR은 단락과 표의 원본 순서를 그대로 보존하므로 문서 흐름을 재구성할 수 있습니다:
Python
from office_oxide import Document
with Document.open("report.docx") as doc:
ir = doc.to_ir()
for section in ir["sections"]:
for el in section["elements"]:
if el["kind"] == "Heading":
print(f"\n## {el['text']}")
elif el["kind"] == "Paragraph":
print(" ".join(r["text"] for r in el["runs"]))
elif el["kind"] == "Table":
for row in el["rows"]:
print("|", " | ".join(row), "|")
PPTX: 슬라이드 섹션 안의 표
각 슬라이드는 독립적인 섹션입니다. 섹션을 순회하면 슬라이드별 컨텍스트를 복원할 수 있습니다:
Python
with Document.open("deck.pptx") as doc:
ir = doc.to_ir()
for i, section in enumerate(ir["sections"], 1):
for el in section["elements"]:
if el["kind"] == "Table":
print(f"slide {i}: {len(el['rows'])}×{len(el['rows'][0])} table")
문자열이 아닌 셀 타입이 필요할 때
IR의 표 표현은 셀을 문자열로 평탄화합니다. XLSX에서 숫자, 텍스트, 불리언을 구분하려면 형식별 접근자를 사용하세요:
Python
with Document.open("budget.xlsx") as doc:
xlsx = doc.as_xlsx()
for sheet in xlsx.sheets():
for cell in sheet.cells():
print(cell.address(), cell.value(), cell.value_type())
더 보기
- 구조화 IR — 전체 스키마
- Markdown 추출 — GFM 파이프 표 자동 출력
- XLSX 셀 설정 — 스프레드시트에 다시 쓰기