tksheet provides built-in formatters for common data types and allows for highly customizable formatting logic. You can apply formatters to specific columns using the .format() method on a column selection.
Built-in Formatters
float_formatter(): Formats floating point numbers.int_formatter(): Formats integers.percentage_formatter(): Formats numbers as percentages. Supports decimals argument.bool_formatter(): Formats boolean values. Supports truthy and falsy sets to define custom truth/false values.
Custom Formatting Logic
You can extend formatting using several hooks:
pre_format_function: A function applied to the raw value before it is processed by the formatter.post_format_function: A function applied to the value after the formatter has processed it.formatter() (Generic Interface): Used for complex types (like datetime). It requires datatypes, format_function (to convert raw data to the target type), and to_str_function (to convert the target type to a display string).
Column Selection
Use num2alpha(index) to convert a zero-based integer index into a spreadsheet-style letter index (e.g., 0 becomes 'A') for column selection.
from tksheet import Sheet, formatter, float_formatter, int_formatter, percentage_formatter, bool_formatter, truthy, falsy, num2alpha
# ... setup sheet ...
# Apply built-in formatters
self.sheet[num2alpha(0)].format(float_formatter(nullable=False))
self.sheet[num2alpha(2)].format(int_formatter())
self.sheet[num2alpha(3)].format(bool_formatter(truthy=truthy | {"nah yeah"}, falsy=falsy | {"yeah nah"}))
self.sheet[num2alpha(4)].format(percentage_formatter())
# Custom formatter with pre/post hooks
self.sheet[num2alpha(7)].format(float_formatter(post_format_function=round_up))
self.sheet[num2alpha(8)].format(float_formatter(), pre_format_function=only_numeric)
# Complex custom formatter (e.g., for datetime)
def convert_to_local_datetime(dt, **kwargs): ...
def datetime_to_string(dt, **kwargs): ...
self.sheet[num2alpha(5)].format(
formatter(
datatypes=datetime,
format_function=convert_to_local_datetime,
to_str_function=datetime_to_string,
nullable=False,
invalid_value="NaT",
)
)