Definir células em XLSX
set_cell(sheet_index, cell_ref, value) escreve um valor em uma worksheet pelo índice da planilha começando em zero e uma referência de célula estilo A1 (A1, B12, AA42). Office Oxide aceita strings, números, booleanos e vazios.
A worksheet em volta — formatos, mesclagens, formatação condicional, intervalos nomeados, gráficos — fica preservada na íntegra.
Escrever 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 também aceito)
ed.set_cell(0, "C1", True) # boolean
ed.set_cell(0, "D1", None) # vazio
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); // boolean
wb.setCell(0, 'D1', null); // vazio
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"); // limpa a célula
wb.Save("budget.xlsx");
Atualizações em lote
Combine várias escritas em um ú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 # linha 1 reservada para cabeçalhos
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")?;
Mirar em outras planilhas
sheet_index é a posição na pasta de trabalho começando em zero — não o nome. Para resolver nome → índice, leia a pasta antes:
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")
O que set_cell mexe e o que não mexe
set_cell escreve o valor <v> e o tipo <t> da célula; ele não:
- Recalcula fórmulas. Para disparar o recalc, abra no Excel ou use um motor de cálculo.
- Mexe na tabela shared-strings além de anexar a nova string. Strings existentes continuam compartilhadas.
- Muda formatação de célula, formatação condicional nem intervalos nomeados.
Se a célula-alvo tem uma fórmula, set_cell sobrescreve a fórmula com o valor estático. Para escrever fórmulas explicitamente, use a API específica de formato xlsx::edit.
Erros
| Sintoma | Causa |
|---|---|
OfficeError::Sheet(idx) (Rust) / IndexError (Python) |
sheet_index ≥ número de planilhas na pasta |
OfficeError::CellRef("...") |
A referência de célula não é A1 válida |
Depois de Number(value) a célula aparece vazia no Excel |
A célula estava formatada como texto — limpe o formato no Excel ou escreva via API de formato |
Veja também
- Substituir texto em DOCX/PPTX
- Visão geral de edição
- Migrar do openpyxl — mesma cobertura XLSX, bem mais rápido