Skip to content

Establecer celdas en XLSX

set_cell(sheet_index, cell_ref, value) escribe un valor en una worksheet por índice de hoja basado en cero y referencia de celda A1 estándar (A1, B12, AA42). Office Oxide acepta strings, números, booleanos y vacíos.

La worksheet alrededor — formatos, combinaciones, formato condicional, rangos con nombre, gráficos — se preserva tal cual.

Escribir tipos básicos

Python

from office_oxide import EditableDocument

with EditableDocument.open("budget.xlsx") as ed:
    ed.set_cell(0, "A1", "Total")     # string
    ed.set_cell(0, "B1", 42.5)        # número (int también vale)
    ed.set_cell(0, "C1", True)        # booleano
    ed.set_cell(0, "D1", None)        # vacío
    ed.save("budget.xlsx")

Rust

use office_oxide::edit::EditableDocument;
use office_oxide::xlsx::edit::CellValue;

let mut wb = EditableDocument::open("budget.xlsx")?;
wb.set_cell(0, "A1", CellValue::String("Total".into()))?;
wb.set_cell(0, "B1", CellValue::Number(42.5))?;
wb.set_cell(0, "C1", CellValue::Boolean(true))?;
wb.set_cell(0, "D1", CellValue::Empty)?;
wb.save("budget.xlsx")?;

JavaScript

import { EditableDocument } from 'office-oxide';

using wb = EditableDocument.open('budget.xlsx');

wb.setCell(0, 'A1', 'Total');   // string
wb.setCell(0, 'B1', 42.5);      // número
wb.setCell(0, 'C1', true);      // booleano
wb.setCell(0, 'D1', null);      // vacío

wb.save('budget.xlsx');

Go

ed, _ := officeoxide.OpenEditable("budget.xlsx")
defer ed.Close()

ed.SetCell(0, "A1", officeoxide.NewStringCell("Total"))
ed.SetCell(0, "B1", officeoxide.NewNumberCell(42.5))
ed.SetCell(0, "C1", officeoxide.NewBoolCell(true))
ed.SetCell(0, "D1", officeoxide.NewEmptyCell())

ed.Save("budget.xlsx")

C#

using var wb = EditableDocument.Open("budget.xlsx");

wb.SetCell(0u, "A1", "Total");        // overload string
wb.SetCell(0u, "B1", 42.5);           // overload double
wb.SetCell(0u, "C1", true);           // overload bool
wb.SetCellEmpty(0u, "D1");            // vacía la celda

wb.Save("budget.xlsx");

Actualizaciones en lote

Combina muchas escrituras en un único ciclo open/save.

Python

rows = [
    ("Acme",    120_000, True),
    ("Globex",   85_000, False),
    ("Initech",  62_500, True),
]

with EditableDocument.open("dashboard.xlsx") as ed:
    for i, (name, revenue, active) in enumerate(rows):
        row = i + 2  # fila 1 para las cabeceras
        ed.set_cell(0, f"A{row}", name)
        ed.set_cell(0, f"B{row}", revenue)
        ed.set_cell(0, f"C{row}", active)
    ed.save("dashboard.xlsx")

Rust

let rows = [
    ("Acme",    120_000.0, true),
    ("Globex",   85_000.0, false),
    ("Initech",  62_500.0, true),
];

let mut ed = EditableDocument::open("dashboard.xlsx")?;
for (i, (name, revenue, active)) in rows.iter().enumerate() {
    let row = i + 2;
    ed.set_cell(0, &format!("A{row}"), CellValue::String((*name).into()))?;
    ed.set_cell(0, &format!("B{row}"), CellValue::Number(*revenue))?;
    ed.set_cell(0, &format!("C{row}"), CellValue::Boolean(*active))?;
}
ed.save("dashboard.xlsx")?;

Apuntar a otras hojas

sheet_index es la posición basada en cero dentro del libro — no el nombre de hoja. Para resolver nombre → índice, lee antes el libro:

Python

from office_oxide import Document, EditableDocument

with Document.open("budget.xlsx") as doc:
    sheet_names = [s.name() for s in doc.as_xlsx().sheets()]
print(sheet_names)   # ['Summary', 'Q1', 'Q2', 'Q3', 'Q4']

idx = sheet_names.index("Q3")
with EditableDocument.open("budget.xlsx") as ed:
    ed.set_cell(idx, "B5", 42_000)
    ed.save("budget.xlsx")

Qué toca set_cell y qué no

set_cell escribe el valor <v> y el tipo <t> de la celda; no:

  • Recalcula fórmulas. Para disparar el recalc abre el archivo en Excel o usa un motor de cálculo.
  • Modifica la tabla shared-strings más allá de añadir la nueva cadena. Las cadenas existentes siguen siendo compartidas.
  • Cambia formato de celda, formato condicional ni rangos con nombre.

Si la celda destino tiene una fórmula, set_cell la sobrescribe con el valor estático. Para escribir fórmulas explícitamente, usa la API específica xlsx::edit.

Errores

Síntoma Causa
OfficeError::Sheet(idx) (Rust) / IndexError (Python) sheet_index ≥ cantidad de hojas en el libro
OfficeError::CellRef("...") La referencia de celda no es A1 válida
Tras Number(value) la celda aparece vacía en Excel La celda estaba formateada como texto — limpia el formato en Excel o escribe con la API específica

Véase también