テーブルを抽出
Office Oxide はテーブルをファーストクラスの IR 要素として扱います: DOCX のすべての <w:tbl>、XLSX のすべての範囲、PPTX のすべての <a:tbl> が型付きの Table { rows: [[セル, ...]] } として返ります。1 つのループで 3 形式すべてを処理。
ドキュメント内のすべてのテーブルを走査
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 §ion.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: シート範囲ごとに 1 テーブル
スプレッドシートの場合、各セクションは 1 つのワークシートに対応し、テーブルは検出された使用範囲に対応します。空のセルは空文字列として出力され、結合セルは左上の値に展開されて残りは空白に。
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 を使用:
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: テーブルはスライドセクション内
各スライドが独自のセクション。スライドごとのコンテキストを取り戻すにはセクションを iterate:
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())
関連項目
- 構造化 IR — 完全なスキーマ
- Markdown 抽出 — GFM パイプテーブルを無料で出力
- XLSX セルの設定 — スプレッドシートに書き戻す