Skip to content

Extrair tabelas

Office Oxide trata tabelas como elementos de primeira classe da IR: cada <w:tbl> em DOCX, cada intervalo em XLSX e cada <a:tbl> em PPTX volta como um Table { rows: [[célula, ...]] } tipado. Um único loop atende três formatos.

Percorrer todas as tabelas de um documento

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: uma tabela por intervalo de planilha

Em planilhas, cada section corresponde a uma worksheet e as tabelas mapeiam aos intervalos usados detectados. Células vazias saem como string vazia; células mescladas se expandem com o conteúdo do canto superior esquerdo, e o resto fica em branco.

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)

Para acesso mais rico por célula (fórmulas, mescladas, intervalos nomeados), entre na API específica do formato:

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

DOCX: tabelas intercaladas com parágrafos

A IR preserva a ordem original de parágrafos e tabelas, então você consegue reconstruir o fluxo:

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: tabelas dentro das sections do slide

Cada slide é a sua própria section. Itere as sections para recuperar o contexto slide a slide:

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}: tabela {len(el['rows'])}×{len(el['rows'][0])}")

Quando você precisa do tipo da célula, não da string

A representação de tabela na IR achata as células para string. Para distinguir número de texto ou boolean em XLSX, use o accessor específico do formato:

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

Veja também