Skip to content

Migración desde python-calamine (y calamine)

calamine es el reputado lector Rust de XLSX/XLS; python-calamine es su binding Python. Ambos se centran exclusivamente en hojas de cálculo.

Office Oxide es 2,8× más rápido que python-calamine en XLSX (5,0 ms frente a 13,9 ms de media en 1.802 archivos), con la mayor tasa de éxito (97,8 % frente a 96,6 %). Encima añade soporte completo para DOCX, PPTX y DOC/PPT heredados — formatos que calamine no lee en absoluto.

Cuándo migrar

Cambia si se cumple alguna de estas condiciones:

  • También necesitas .docx / .pptx / .doc / .ppt (calamine es solo XLSX/XLS)
  • Quieres un conjunto de funciones más amplio: salida Markdown / HTML, IR estructurado, plantillas con EditableDocument
  • La tasa de éxito importa más que la pequeña ventaja de rendimiento que calamine tiene en ciertos escenarios
  • Estás sobre el binding Python y quieres menos conversiones cross-FFI

Sigue con calamine si:

  • Solo lees .xlsx y .xls
  • Dependes de APIs específicas de calamine (Reader::with_header_row, worksheet_range_at, etc.)
  • Necesitas expresiones de fórmula (calamine las expone; el IR de Office Oxide no)

Instalación (Python)

pip uninstall python-calamine
pip install office-oxide

Instalación (Rust)

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

Chuleta comparativa — Python

Abrir un libro

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 hojas

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)

Leer una sola hoja como filas

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 un camino más directo:

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

Nombres de hojas

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

Chuleta comparativa — 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 al formato (sin equivalente en calamine)

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

Es la misma forma que obtendrías de un .docx o un .pptx — útil cuando los consumidores downstream no deben preocuparse del formato de origen.

Escritura de XLSX

calamine es solo lectura. Office Oxide escribe celdas XLSX con 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 construcción completa de XLSX, baja a xlsx::create::XlsxBuilder o usa umya-spreadsheet / rust_xlsxwriter.

Rendimiento

Biblioteca XLSX Media p99 Tasa de éxito
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 Media p99 Tasa de éxito
office_oxide 2,8 ms 75 ms 99,2 %
python-calamine 9,0 ms 96 ms 90,7 %

En qué se diferencian

calamine devuelve un enum Data tipado por celda (Int, Float, String, Bool, DateTime, Empty, Error). El IR de Office Oxide colapsa a cadenas; para acceso tipado a la celda, usa el accesor específico del 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"

Ver también