Codumentor logo Codumentor Enterprise

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:

GroupNames
Session workbookswb (editable, formula strings), wb_cached (original-open data_only=True snapshot)
Workbook constructorWorkbook
StylesFont, PatternFill, Alignment, Border, Side, NamedStyle
ChartsReference, BarChart, LineChart, PieChart, ScatterChart
Conditional formattingRule, FormulaRule, CellIsRule, ColorScaleRule, DataBarRule, IconSetRule
Data validationDataValidation
Coordinatesget_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

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.