Skip to content

Commit

Permalink
fix(python): Improve default write_excel int/float format when usin…
Browse files Browse the repository at this point in the history
…g an explicit "table_style"
  • Loading branch information
alexander-beedie committed Jul 25, 2024
1 parent 3016c07 commit 9fe6ab1
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 8 deletions.
1 change: 1 addition & 0 deletions py-polars/polars/dataframe/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -3186,6 +3186,7 @@ def write_excel(
dtype_formats=dtype_formats,
header_format=header_format,
float_precision=float_precision,
table_style=table_style,
row_totals=row_totals,
sparklines=sparklines,
formulas=formulas,
Expand Down
19 changes: 12 additions & 7 deletions py-polars/polars/io/spreadsheet/_write_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,6 @@ def _cluster(iterable: Iterable[Any], n: int = 2) -> Iterable[Any]:
Date: "yyyy-mm-dd;@",
Time: "hh:mm:ss;@",
}
for tp in INTEGER_DTYPES:
_XL_DEFAULT_DTYPE_FORMATS_[tp] = _XL_DEFAULT_INTEGER_FORMAT_


class _XLFormatCache:
Expand Down Expand Up @@ -331,6 +329,7 @@ def _xl_setup_table_columns(
formulas: dict[str, str | dict[str, str]] | None = None,
row_totals: RowTotalsDefinition | None = None,
float_precision: int = 3,
table_style: dict[str, Any] | str | None = None,
) -> tuple[list[dict[str, Any]], dict[str | tuple[str, ...], str], DataFrame]:
"""Setup and unify all column-related formatting/defaults."""

Expand Down Expand Up @@ -429,12 +428,18 @@ def _map_str(s: Series) -> Series:
fmt_default = format_cache.get({"valign": "vcenter"})

# default float format
if table_style is None:
int_base_fmt = _XL_DEFAULT_INTEGER_FORMAT_
flt_base_fmt = _XL_DEFAULT_FLOAT_FORMAT_
else:
int_base_fmt = _XL_DEFAULT_INTEGER_FORMAT_.split(";", 1)[0]
flt_base_fmt = _XL_DEFAULT_FLOAT_FORMAT_.split(";", 1)[0]

for tp in INTEGER_DTYPES:
_XL_DEFAULT_DTYPE_FORMATS_[tp] = int_base_fmt

zeros = "0" * float_precision
fmt_float = (
_XL_DEFAULT_INTEGER_FORMAT_
if not zeros
else _XL_DEFAULT_FLOAT_FORMAT_.replace(".000", f".{zeros}")
)
fmt_float = int_base_fmt if not zeros else flt_base_fmt.replace(".000", f".{zeros}")

# assign default dtype formats
for tp, fmt in _XL_DEFAULT_DTYPE_FORMATS_.items():
Expand Down
2 changes: 1 addition & 1 deletion py-polars/tests/unit/io/test_spreadsheet.py
Original file line number Diff line number Diff line change
Expand Up @@ -545,7 +545,7 @@ def test_read_excel_all_sheets_with_sheet_name(path_xlsx: Path, engine: str) ->
# basic formatting
{
"autofit": True,
"table_style": "Table Style Light 16",
"table_style": "Table Style Dark 2",
"column_totals": True,
"float_precision": 0,
},
Expand Down

0 comments on commit 9fe6ab1

Please sign in to comment.