Skip to content

표 추출

Office Oxide는 표를 일급 IR 요소로 다룹니다: DOCX의 모든 <w:tbl>, XLSX의 모든 범위, PPTX의 모든 <a:tbl>이 타입화된 Table { rows: [[셀, ...]] }로 돌아옵니다. 루프 하나로 세 형식 모두 처리.

문서 안의 모든 표 순회

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)

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 &section.elements {
        if let Element::Table(t) = el {
            for row in &t.rows {
                println!("{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())));
        }
    }
}

XLSX: 시트 범위마다 표 하나

스프레드시트의 경우 각 섹션이 워크시트에 해당하고, 표는 감지된 used range에 매핑됩니다. 빈 셀은 빈 문자열로 나오고, 병합 셀은 좌상단 값으로 펼쳐지며 나머지는 빈 칸이 됩니다.

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)

셀 단위의 더 풍부한 접근(수식, 병합 셀, 이름 있는 범위)이 필요하면 형식별 모듈로 들어가세요:

with Document.open("budget.xlsx") as doc:
    xlsx = doc.as_xlsx()
    for sheet in xlsx.sheets():
        print(sheet.name(), sheet.dimensions())

DOCX: 표가 단락과 섞임

IR은 단락과 표의 원본 순서를 보존하므로 흐름을 재구성할 수 있습니다:

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: 표는 슬라이드 섹션 안에

각 슬라이드가 자체 섹션입니다. 슬라이드별 컨텍스트를 되살리려면 섹션을 순회하세요:

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"슬라이드 {i}: {len(el['rows'])}×{len(el['rows'][0])} 표")

셀 타입이 필요할 때(문자열이 아니라)

IR의 표 표현은 셀을 문자열로 평탄화합니다. XLSX에서 숫자, 텍스트, 불리언을 구분하려면 형식별 접근자를 사용하세요:

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())

더 보기