Skip to content

Migração a partir do python-calamine (e calamine)

calamine é o conhecido leitor Rust de XLSX/XLS; python-calamine é o seu binding para Python. Ambos focam exclusivamente em planilhas.

O Office Oxide é 2,8× mais rápido que o python-calamine em XLSX (5,0 ms contra 13,9 ms em média em 1.802 arquivos), com a maior taxa de sucesso (97,8% contra 96,6%). Ele ainda adiciona suporte completo a DOCX, PPTX e DOC/PPT legados — formatos que o calamine não lê.

Quando migrar

Troque se qualquer uma destas condições se aplica:

  • Você também precisa de .docx / .pptx / .doc / .ppt (calamine é só XLSX/XLS)
  • Quer um conjunto de recursos mais amplo: saída Markdown / HTML, IR estruturado, templating via EditableDocument
  • Taxa de sucesso importa mais do que a pequena vantagem de performance do calamine em alguns cenários
  • Você está no binding Python e quer menos conversões entre FFI

Fique no calamine se:

  • Você só lê .xlsx e .xls
  • Depende de APIs específicas do calamine (Reader::with_header_row, worksheet_range_at etc.)
  • Precisa de expressões de fórmula (o calamine as expõe; o IR do Office Oxide não)

Instalação (Python)

pip uninstall python-calamine
pip install office-oxide

Instalação (Rust)

# Cargo.toml
[dependencies]
# Substituir:
#   calamine = "0.30"
office_oxide = "0.1.0"

Guia rápido lado a lado — Python

Abrir uma pasta de trabalho

python-calamine

from python_calamine import CalamineWorkbook

wb = CalamineWorkbook.from_path("budget.xlsx")

office_oxide

from office_oxide import Document

with Document.open("budget.xlsx") as doc:
    ...

Iterar planilhas

python-calamine

for name in wb.sheet_names:
    sheet = wb.get_sheet_by_name(name)
    for row in sheet.to_python():
        print(row)

office_oxide

with Document.open("budget.xlsx") as doc:
    ir = doc.to_ir()

for section in ir["sections"]:
    print(f"# {section.get('title')}")
    for el in section["elements"]:
        if el["kind"] == "Table":
            for row in el["rows"]:
                print(row)

Ler uma única planilha como linhas

python-calamine

sheet = wb.get_sheet_by_name("Q4")
rows = sheet.to_python()

office_oxide

with Document.open("budget.xlsx") as doc:
    table = next(
        el for section in doc.to_ir()["sections"]
        if section.get("title") == "Q4"
        for el in section["elements"] if el["kind"] == "Table"
    )
    rows = table["rows"]

Para um caminho mais direto:

with Document.open("budget.xlsx") as doc:
    sheet = doc.as_xlsx().sheet("Q4")
    rows = sheet.rows()    # list[list[str]]

Nomes das planilhas

python-calamine

print(wb.sheet_names)

office_oxide

with Document.open("budget.xlsx") as doc:
    print([s.name() for s in doc.as_xlsx().sheets()])

Guia rápido lado a lado — Rust

Abrir e iterar

calamine

use calamine::{open_workbook, Xlsx, Reader};

let mut wb: Xlsx<_> = open_workbook("budget.xlsx")?;
for sheet_name in wb.sheet_names() {
    if let Ok(range) = wb.worksheet_range(&sheet_name) {
        for row in range.rows() {
            println!("{row:?}");
        }
    }
}

office_oxide

use office_oxide::Document;

let doc = Document::open("budget.xlsx")?;
if let Some(xlsx) = doc.as_xlsx() {
    for sheet in xlsx.sheets() {
        for cell in sheet.cells() {
            println!("{}: {:?}", cell.address(), cell.value());
        }
    }
}

IR agnóstico de formato (sem equivalente no calamine)

let doc = Document::open("budget.xlsx")?;
let ir = doc.to_ir();
serde_json::to_writer(std::io::stdout(), &ir)?;

É a mesma forma que você obteria de um .docx ou .pptx — útil quando consumidores downstream não devem se preocupar com o formato de origem.

Escrita em XLSX

O calamine é somente leitura. O Office Oxide escreve células XLSX via EditableDocument:

from office_oxide import EditableDocument

with EditableDocument.open("budget.xlsx") as ed:
    ed.set_cell(0, "B5", 42_000)
    ed.save("budget.xlsx")

Para construção completa de XLSX, desça até xlsx::create::XlsxBuilder ou use umya-spreadsheet / rust_xlsxwriter.

Desempenho

Biblioteca XLSX Média p99 Taxa de sucesso
office_oxide 5,0 ms 40 ms 97,8%
python-calamine 13,9 ms 183 ms 96,6%
openpyxl 94,5 ms 698 ms 96,2%
Biblioteca XLS Média p99 Taxa de sucesso
office_oxide 2,8 ms 75 ms 99,2%
python-calamine 9,0 ms 96 ms 90,7%

O que é diferente

O calamine retorna um enum Data tipado por célula (Int, Float, String, Bool, DateTime, Empty, Error). O IR do Office Oxide colapsa para strings; para acesso tipado, use o acessor específico do formato:

with Document.open("budget.xlsx") as doc:
    for sheet in doc.as_xlsx().sheets():
        for cell in sheet.cells():
            print(cell.value(), cell.value_type())   # value_type: "string" | "number" | "boolean" | "empty"

Veja também