Análise de tabela Aspose.Note FOSS para Python
As tabelas nos documentos do OneNote são expostas numa hierarquia de três níveis: Table → TableRow → TableCell.Cada célula pode conter: RichText, Image,Esta página abrange todos os padrões de análise de tabelas suportados pelo Aspose. Nota FOSS para Python.
Iteração básica da tabela
Obter todas as tabelas do documento e ler o texto das células:
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}")Propriedades da tabela
| Propriedade | Tipo de veículo: | Descrição: |
|---|---|---|
Columns | list[TableColumn] | Definições de colunas; cada uma delas TableColumn tem .Width (flutuante) e .LockedWidth - Não . |
IsBordersVisible | bool | Se as bordas da tabela estão exibidas |
Tags | list[NoteTag] | Etiquetas do OneNote anexadas à tabela |
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}")Tabela de exportação para CSV
Converter uma tabela para 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())Extrair tabelas por página
Extracção de tabela do âmbito para páginas individuais:
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}")Conteúdo da célula para além do texto simples
As células da tabela podem conter: Image e outros CompositeNode conteúdo ao lado de 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 e resumir tabelas
Reunir estatísticas sobre todas as tabelas num 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]}")Inspecionar etiquetas nas mesas
Suporte de tabelas NoteTag Itens 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}")Posição das tabelas DOM
As tabelas aparecem como filhos de: OutlineElement Nodos dentro de: Outline Em cada recipiente, Page.A hierarquia é:
Page
└── Outline
└── OutlineElement
└── Table
└── TableRow
└── TableCell
└── RichText / ImageTambém pode aceder às mesas através do sítio: GetChildNodes(Table) em qualquer nível de nó ancestral, e busca a sub-árvore completa.
Dicas de trabalho
table.Columnsé uma lista de:TableColumnobjetos; uso[col.Width for col in table.Columns]O comprimento é igual ao número de colunas.- O conteúdo das células não é sempre puramente
RichText;Sempre verificar se há:ImageOs nós também, se a fidelidade total importa. - Utilização:
table.GetChildNodes(TableRow)em vez de iterarfor row in tablese você precisa de uma lista digitada em vez de um iterador genérico. IsBordersVisibleReflecte a preferência de exibição do utilizador no momento da salva; não afecta a extracção de conteúdo.