Análisis de tablas — Aspose.Note FOSS para Python

Las tablas en los documentos de OneNote se exponen como una jerarquía de tres niveles: Table → TableRow → TableCell. Cada celda puede contener RichText, Image, y otros nodos de contenido. Esta página cubre todos los patrones de análisis de tablas compatibles con Aspose.Note FOSS para Python.


Iteración básica de tablas

Obtén todas las tablas del documento y lee el texto de sus celdas:

from aspose.note import Document, Table, TableRow, TableCell, RichText

doc = Document("MyNotes.one")

for table_num, table in enumerate(doc.GetChildNodes(Table), start=1):
    print(f"\nTable {table_num}: {len(table.Columns)} column(s)")
    for r, row in enumerate(table.GetChildNodes(TableRow), start=1):
        cells = row.GetChildNodes(TableCell)
        values = [
            " ".join(rt.Text for rt in cell.GetChildNodes(RichText)).strip()
            for cell in cells
        ]
        print(f"  Row {r}: {values}")

Propiedades de la tabla

PropiedadTipoDescripción
Columnslist[TableColumn]Definiciones de columna; cada TableColumn tiene .Width (float) y .LockedWidth (bool)
IsBordersVisibleboolSi se muestran los bordes de la tabla
Tagslist[NoteTag]Etiquetas de OneNote adjuntas a la tabla
from aspose.note import Document, Table

doc = Document("MyNotes.one")
for table in doc.GetChildNodes(Table):
    print(f"Columns: {len(table.Columns)}")
    print(f"Widths (pts): {[col.Width for col in table.Columns]}")
    print(f"Borders visible: {table.IsBordersVisible}")

Exportar tabla a CSV

Convertir una tabla al formato CSV:

import csv
import io
from aspose.note import Document, Table, TableRow, TableCell, RichText

doc = Document("MyNotes.one")
output = io.StringIO()
writer = csv.writer(output)

for table in doc.GetChildNodes(Table):
    for row in table.GetChildNodes(TableRow):
        values = [
            " ".join(rt.Text for rt in cell.GetChildNodes(RichText)).strip()
            for cell in row.GetChildNodes(TableCell)
        ]
        writer.writerow(values)
    writer.writerow([])  # blank line between tables

print(output.getvalue())

Extraer tablas por página

Limita la extracción de tablas a páginas individuales:

from aspose.note import Document, Page, Table, TableRow, TableCell, RichText

doc = Document("MyNotes.one")
for page_num, page in enumerate(doc.GetChildNodes(Page), start=1):
    tables = page.GetChildNodes(Table)
    if not tables:
        continue
    title = (
        page.Title.TitleText.Text
        if page.Title and page.Title.TitleText
        else f"Page {page_num}"
    )
    print(f"\n=== {title} ({len(tables)} table(s)) ===")
    for t, table in enumerate(tables, start=1):
        print(f"  Table {t}:")
        for row in table.GetChildNodes(TableRow):
            cells = row.GetChildNodes(TableCell)
            row_text = [
                " ".join(rt.Text for rt in cell.GetChildNodes(RichText)).strip()
                for cell in cells
            ]
            print(f"    {row_text}")

Contenido de la celda más allá del texto plano

Las celdas de la tabla pueden contener Image y otros CompositeNode contenido junto a RichText:

from aspose.note import Document, Table, TableRow, TableCell, RichText, Image

doc = Document("MyNotes.one")
for table in doc.GetChildNodes(Table):
    for row in table.GetChildNodes(TableRow):
        for cell in row.GetChildNodes(TableCell):
            texts = [rt.Text for rt in cell.GetChildNodes(RichText) if rt.Text]
            images = cell.GetChildNodes(Image)
            print(f"  Cell texts: {texts}  images: {len(images)}")

Contar y resumir tablas

Recopila estadísticas sobre todas las tablas de un documento:

from aspose.note import Document, Table, TableRow, TableCell

doc = Document("MyNotes.one")
tables = doc.GetChildNodes(Table)
print(f"Total tables: {len(tables)}")

for i, table in enumerate(tables, start=1):
    rows = table.GetChildNodes(TableRow)
    if rows:
        cols = len(rows[0].GetChildNodes(TableCell))
    else:
        cols = 0
    print(f"  Table {i}: {len(rows)} row(s) x {cols} column(s)  widths={[col.Width for col in table.Columns]}")

Inspeccionar etiquetas en tablas

Las tablas admiten NoteTag elementos directamente:

from aspose.note import Document, Table, TagStatus

doc = Document("MyNotes.one")
for table in doc.GetChildNodes(Table):
    for tag in table.Tags:
        is_completed = tag.Status == TagStatus.Completed
        print(f"Table tag: {tag.Label}  icon={tag.Icon}  completed={is_completed}")

Posición DOM de Tablas

Las tablas aparecen como hijas de OutlineElement nodos dentro de Outline contenedores en cada Page. La jerarquía es:

Page
  └── Outline
        └── OutlineElement
              └── Table
                    └── TableRow
                          └── TableCell
                                └── RichText / Image

También puedes acceder a las tablas a través de GetChildNodes(Table) en cualquier nivel de nodo ancestro, y busca todo el subárbol.


Consejos

  • table.Columns es una lista de TableColumn objetos; utilice [col.Width for col in table.Columns] para obtener los anchos de columna en puntos. La longitud equivale al número de columnas.
  • El contenido de la celda no siempre es puramente RichText; siempre verifique Image nodos también si la fidelidad completa importa.
  • Utilice table.GetChildNodes(TableRow) en lugar de iterar for row in table si necesita una lista tipada en lugar de un iterador genérico.
  • IsBordersVisible refleja la preferencia de visualización del usuario de OneNote al guardar; no afecta la extracción de contenido.

Ver también

 Español