Spreadsheet scripting reference
Use xlsx_python for advanced workbook edits that the dedicated tools do not cover, including conditional formatting and data validation. There are no dedicated tools for these two operations; scripting is the intended escape hatch. Work on wb, then call xlsx_save to persist changes.
Available globals and imports
No module objects are preloaded. The following names are available directly:
| Group | Names |
|---|---|
| Session workbooks | wb (editable, formula strings), wb_cached (original-open data_only=True snapshot) |
| Workbook constructor | Workbook |
| Styles | Font, PatternFill, Alignment, Border, Side, NamedStyle |
| Charts | Reference, BarChart, LineChart, PieChart, ScatterChart |
| Conditional formatting | Rule, FormulaRule, CellIsRule, ColorScaleRule, DataBarRule, IconSetRule |
| Data validation | DataValidation |
| Coordinates | get_column_letter, column_index_from_string, coordinate_from_string, range_boundaries |
The restricted builtins are:
bool int float str bytes bytearray list tuple dict set frozenset
range enumerate zip map filter reversed iter next
len sum min max abs round sorted any all
repr format chr ord isinstance issubclass hasattr
True False None print
Exception ValueError TypeError KeyError IndexError AttributeError
RuntimeError StopIteration
getattr setattr delattr (string-literal public attribute name only)
Imports work only for the authoring modules listed under modules by office_capabilities() — for example from openpyxl.styles import Font, from openpyxl.chart import AreaChart, import openpyxl.utils as u. They return the same read-only module proxies; workbook reading/writing (load_workbook, openpyxl.reader, openpyxl.writer, …), other modules (os, datetime, …), from x import * and relative imports are refused with an error naming the nearest available path.
Set a top-level result variable to return a value; print() output is captured, not streamed live (at most 8,000 characters plus a truncation notice). Private/dunder attribute access and dangerous calls such as open, exec, eval, compile, __import__, globals, locals, vars, dir, and type are rejected; getattr/setattr/delattr are accepted only with a string-literal public name (setattr(ws, "title", "Data") is ws.title = "Data"). date/datetime are preloaded classes, not importable modules. Each rejection says what to write instead.
Formula reads and the cached snapshot
wbcontains the live editable workbook. A formula cell's.valueis its formula text, not a calculated result.wb_cachedis a separate workbook loaded withdata_only=Truewhen opening the file. For a newly created workbook it is loaded from the initial blank file. It is not recalculated or refreshed by writes or saves; closing discards it, and opening again loads a new snapshot from disk. Treat it as read-only: scripts technically receive a workbook object, so mutating it would corrupt your session's snapshot without updatingwb.wb_cached["Sheet1"]["A1"].valuereturns the raw snapshot value. If no cached formula result exists it returnsNone; there is no automatic formula fallback in this Python expression.xlsx_read_rangereturns live literal values and formula text by default. Withuse_cached=true, unchanged formula cells use their original cached results; new, changed, moved, or uncached formulas fall back to formula text. Literal cells still use their live values. Formula metadata identifies cache availability and array/data-table anchors.include_formulasremains a compatibility flag; it is not necessary for default formula reads and is ignored withuse_cached=true.- Original array/data-table follower values are suppressed on reads and cleared on save if their anchor changes, moves, or disappears, unless those follower cells were explicitly replaced with different values/types or cell objects. Assigning the identical value/type to the same follower object is indistinguishable from leaving it untouched. Missing cached results at a formula anchor return formula text, not a bare
null; genuinely empty cells and invalidated follower results can still returnnull.
Saving is not calculation. Cached results can be missing or stale, including when only a precedent/input cell changes and the dependent formula text stays identical. Do not treat preserved caches as proof that formulas have been evaluated against the edited workbook. New or modified formulas may have no cached result; non-recalculating viewers can show blanks. Volatile formulas (for example NOW() or RAND()) need recalculation too. Dynamic-array formulas such as UNIQUE() require a compatible calculation application; their cached/spilled results can be missing or stale. Open the saved file in a compatible Excel or LibreOffice version and recalculate before relying on computed values. Reopening in Codumentor alone does not calculate anything.
Conditional formatting example
Run this as the code argument of xlsx_python (adapt Sheet1 and the range):
ws = wb["Sheet1"]
red = PatternFill(fill_type="solid", fgColor="FFC7CE")
ws.conditional_formatting.add(
"B2:B100",
FormulaRule(formula=['B2="Late"'], fill=red),
)
ws.conditional_formatting.add(
"C2:C100",
CellIsRule(operator="lessThan", formula=["0"], fill=red),
)
result = "Added status and negative-value rules"
Rule formulas use openpyxl's formula syntax without a leading =; relative references are based on the first cell in the target range. ColorScaleRule, DataBarRule, and IconSetRule support their corresponding rule types. Rule is the lower-level constructor; use the convenience constructors for common rules. These edits store rule definitions; the spreadsheet application renders/evaluates them.
Data validation example
ws = wb["Sheet1"]
validation = DataValidation(
type="list", formula1='"Todo,Doing,Done"', allow_blank=True,
)
validation.errorTitle = "Invalid status"
validation.error = "Choose Todo, Doing, or Done."
validation.showErrorMessage = True
ws.add_data_validation(validation)
validation.add("B2:B100")
result = "Added status dropdown"
Attach the validation to the worksheet and add a target range. Rules are stored for the spreadsheet application to enforce; they do not retroactively validate existing cells, and Python writes are not checked against them. Save after either example with xlsx_save.