Skip to content

Commit b2fc17f

Browse files
33modelingrusackassadpandajoe
authored
fix(csv): honor decimal separators in object-valued numeric cells (#45782)
Signed-off-by: 33modeling <33modeling@gmail.com> Co-authored-by: Evan Rusackas <evan@preset.io> Co-authored-by: Joe Li <joe@preset.io>
1 parent d3d8f91 commit b2fc17f

5 files changed

Lines changed: 157 additions & 30 deletions

File tree

‎docs/admin_docs/configuration/configuring-superset.mdx‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -145,6 +145,34 @@ D3_TIME_FORMAT = {
145145
Restart Superset after changing `superset_config.py` so the frontend receives
146146
the updated formatter configuration.
147147

148+
## CSV decimal separators
149+
150+
CSV exports contain data values rather than the chart's D3 display strings.
151+
Configure the export delimiter and decimal separator independently of the UI
152+
language in `superset_config.py`, for example:
153+
154+
```python
155+
CSV_EXPORT = {"encoding": "utf-8-sig", "sep": ";", "decimal": ","}
156+
```
157+
158+
This writes `12,3400` for a database decimal value of `12.3400` and `1,25` for
159+
a floating-point value of `1.25`, including numeric cells in mixed object
160+
columns. Direct CSV serialization preserves Decimal precision and trailing zeros.
161+
CSV reports for table and pivot table charts, and pivoted CSV exports, pass
162+
through client-side post-processing that re-reads CSV data and infers numeric
163+
types. Those paths can drop trailing zeros (for example, `12.3400` becomes
164+
`12.34`, or `12,3400` becomes `12,34` with `decimal=","`). Text values
165+
such as `"1.25"` keep their contents, and spreadsheet formula protection
166+
still applies to strings. Streaming CSV exports use the same decimal
167+
separator. The default separator remains `.`.
168+
Duplicate row labels and repeated verbose column names preserve each cell's
169+
value independently when formatting and escaping CSV exports.
170+
171+
Changing `BABEL_DEFAULT_LOCALE` or a chart's number format does not set these
172+
CSV options. These settings also do not convert numeric XLSX cells into
173+
localized text; spreadsheet applications render numeric cells according to
174+
the workbook and application settings.
175+
148176
## Serving translated language packs
149177

150178
Non-English page loads need the frontend translation catalog (the "language

‎superset/commands/sql_lab/export.py‎

Lines changed: 0 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@
1717
from __future__ import annotations
1818

1919
import logging
20-
from decimal import Decimal
2120
from typing import Any, cast, TypedDict
2221

2322
import pandas as pd
@@ -38,17 +37,6 @@
3837
logger = logging.getLogger(__name__)
3938

4039

41-
def _format_decimal_columns(df: pd.DataFrame) -> None:
42-
"""Format decimal object columns without changing other values or dtypes."""
43-
for name, column in df.items():
44-
if pd.api.types.is_object_dtype(column.dtype) and any(
45-
isinstance(value, Decimal) and value.is_finite() for value in column
46-
):
47-
# A finite decimal becomes a string, keeping map's result object-typed
48-
# so mixed floats, integers and None do not undergo dtype inference.
49-
df[name] = column.map(csv.format_decimal)
50-
51-
5240
class SqlExportResult(TypedDict):
5341
query: Query
5442
count: int
@@ -152,8 +140,6 @@ def run(
152140
self._query.schema,
153141
)[:limit]
154142

155-
_format_decimal_columns(df)
156-
157143
# Manual encoding using the specified encoding (default to utf-8 if not set)
158144
csv_string = csv.df_to_escaped_csv(df, index=False, **app.config["CSV_EXPORT"])
159145
csv_data = csv_string.encode(app.config["CSV_EXPORT"].get("encoding", "utf-8"))

‎superset/utils/csv.py‎

Lines changed: 30 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
import urllib.request
1919
from contextlib import closing
2020
from decimal import Decimal
21+
from numbers import Real
2122
from typing import Any, Optional, Union
2223
from urllib.error import URLError
2324

@@ -95,6 +96,22 @@ def format_decimal(value: Any) -> Any:
9596
)
9697

9798

99+
def _escape_csv_cell(value: Any, decimal_separator: str) -> Any:
100+
if isinstance(value, str):
101+
return escape_value(value)
102+
if isinstance(value, Decimal) and value.is_finite():
103+
# Preserve precision without applying formula escaping to numeric text.
104+
return format_decimal(value).replace(".", decimal_separator)
105+
if (
106+
decimal_separator != "."
107+
and isinstance(value, Real)
108+
and not isinstance(value, (bool, int))
109+
and pd.notna(value)
110+
):
111+
return str(value).replace(".", decimal_separator)
112+
return value
113+
114+
98115
def df_to_escaped_csv(df: pd.DataFrame, **kwargs: Any) -> Any:
99116
def escape_values(v: Any) -> Union[str, Any]:
100117
return escape_value(v) if isinstance(v, str) else v
@@ -119,18 +136,18 @@ def escape_axis_level(level: pd.Index) -> pd.Index:
119136
# Escape csv headers
120137
df = df.rename(columns=escape_values)
121138

122-
# Escape csv values. Iterate by index label (via ``items``) rather than by
123-
# positional offset so the escaped value is written back to the correct row
124-
# even when the DataFrame has a non-default index (e.g. the flattened
125-
# MultiIndex produced by pivot_table_v2 post-processing). Pairing positional
126-
# indices with the label-based ``.at`` accessor would otherwise create
127-
# phantom rows and corrupt the output. Only string cells are reassigned, so
128-
# the dtype of mixed object columns (e.g. nullable integers) is preserved.
129-
for name, column in df.items():
139+
# Escape by physical position: row labels and verbose column names can
140+
# repeat after pivot/flatten. Label-based assignment would overwrite every
141+
# matching cell. Keep numeric dtypes for pandas; explicitly format numbers
142+
# only in object columns, matching streaming CSV exports.
143+
decimal_separator = kwargs.get("decimal", ".")
144+
for column_position, (_, column) in enumerate(df.items()):
130145
if pd.api.types.is_string_dtype(column.dtype):
131-
for label, value in column.items():
132-
if isinstance(value, str):
133-
df.at[label, name] = escape_value(value)
146+
escaped = [_escape_csv_cell(value, decimal_separator) for value in column]
147+
df.isetitem(
148+
column_position,
149+
pd.Series(escaped, index=column.index, dtype=column.dtype),
150+
)
134151

135152
# Row labels and axis names are written out whenever the caller asks for the
136153
# index, which both export paths do once post-processing has replaced the
@@ -167,8 +184,8 @@ def escape_axis_level(level: pd.Index) -> pd.Index:
167184
# and the levels of a ``MultiIndex`` have to be unique. Reading the
168185
# row values and factorizing folds a collision onto one code.
169186
rebuilt = [
170-
pd.factorize(values.map(escape_values))
171-
if needs_escaping(values := index.get_level_values(position))
187+
pd.factorize(row_values.map(escape_values))
188+
if needs_escaping(row_values := index.get_level_values(position))
172189
else (index.codes[position], level)
173190
for position, level in enumerate(index.levels)
174191
]

‎tests/unit_tests/commands/sql_lab/export_test.py‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,6 @@ def test_csv_export_mixed_frame_is_byte_identical(
9191
mock_db: MagicMock = mocker.patch("superset.commands.sql_lab.export.db")
9292
query_result: MagicMock = mock_db.session.query.return_value.filter_by.return_value
9393
query_result.one_or_none.return_value = query
94-
formatter: MagicMock = mocker.spy(csv, "format_decimal")
9594

9695
result = SqlResultExportCommand("client_id").run()
9796

@@ -104,10 +103,10 @@ def test_csv_export_mixed_frame_is_byte_identical(
104103
";5.0;5\n"
105104
)
106105
if decimal_separator == ",":
107-
# Pandas applies the separator to float columns, not mixed object cells.
106+
# Every typed numeric cell follows the export separator.
107+
expected = expected.replace("12.3400", "12,3400").replace("\n1.25;", "\n1,25;")
108108
expected = expected.replace(";1.25;", ";1,25;").replace(";2.5;", ";2,5;")
109109
expected = expected.replace(";3.75;", ";3,75;").replace(";4.0;", ";4,0;")
110110
expected = expected.replace(";5.0;", ";5,0;")
111111
assert result["data"] == expected.encode()
112112
assert result["count"] == 5
113-
assert formatter.call_count == 5

‎tests/unit_tests/utils/csv_tests.py‎

Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
# under the License.
1717

1818

19+
from decimal import Decimal
1920
from typing import Any
2021
from unittest import mock
2122

@@ -785,3 +786,99 @@ def test_get_chart_csv_data_closes_response(
785786
== b"csv"
786787
)
787788
response.close.assert_called_once()
789+
790+
791+
@pytest.mark.parametrize("decimal_separator", [".", ","])
792+
@pytest.mark.parametrize("amount", ["12.3400", "-1.25", "0E-18"])
793+
def test_csv_export_honors_decimal_separator_for_exact_values(
794+
decimal_separator: str, amount: str
795+
) -> None:
796+
"""Typed decimals keep their scale and match the float column's separator."""
797+
frame = pd.DataFrame(
798+
{"amount": [Decimal(amount)], "float": [1.25], "text": ["keep.this"]}
799+
)
800+
expected_amount = format(Decimal(amount), "f").replace(".", decimal_separator)
801+
expected_float = "1.25".replace(".", decimal_separator)
802+
result = df_to_escaped_csv(frame, index=False, sep=";", decimal=decimal_separator)
803+
assert (
804+
result == f"amount;float;text\n{expected_amount};{expected_float};keep.this\n"
805+
)
806+
807+
808+
@pytest.mark.parametrize("decimal_separator", [".", ","])
809+
def test_csv_export_honors_decimal_separator_for_mixed_numbers(
810+
decimal_separator: str,
811+
) -> None:
812+
"""Mixed numeric cells match streaming exports without localizing strings."""
813+
frame = pd.DataFrame(
814+
{"mixed": [Decimal("-12.3400"), 1.25, True, "1.25", "=formula", None]},
815+
dtype=object,
816+
)
817+
amount = "-12.3400".replace(".", decimal_separator)
818+
number = "1.25".replace(".", decimal_separator)
819+
assert df_to_escaped_csv(
820+
frame, index=False, decimal=decimal_separator, sep=";"
821+
) == (f'mixed\n{amount}\n{number}\nTrue\n1.25\n\'=formula\n""\n')
822+
823+
824+
@pytest.mark.parametrize("decimal_separator", [".", ","])
825+
@pytest.mark.parametrize(
826+
"duplicate_axis", ["unique", "index", "columns", "both", "multiindex"]
827+
)
828+
def test_csv_export_preserves_duplicate_labels(
829+
decimal_separator: str, duplicate_axis: str
830+
) -> None:
831+
"""Formatting a cell must not overwrite another row or column with its label."""
832+
frame = pd.DataFrame(
833+
[
834+
[Decimal("1.2500"), Decimal("3.7500")],
835+
[Decimal("2.5000"), Decimal("4.2500")],
836+
],
837+
columns=["amount", "amount"]
838+
if duplicate_axis in {"columns", "both"}
839+
else ["first", "second"],
840+
index=["group", "group"]
841+
if duplicate_axis in {"index", "both"}
842+
else ["first", "second"],
843+
)
844+
if duplicate_axis == "multiindex":
845+
frame.index = pd.MultiIndex.from_tuples([("group", 1), ("group", 1)])
846+
original = frame.copy(deep=True)
847+
expected_values = "1.2500;3.7500\n2.5000;4.2500\n".replace(".", decimal_separator)
848+
expected_header = ";".join(frame.columns)
849+
850+
assert (
851+
df_to_escaped_csv(frame, index=False, sep=";", decimal=decimal_separator)
852+
== f"{expected_header}\n{expected_values}"
853+
)
854+
pd.testing.assert_frame_equal(frame, original)
855+
856+
857+
@pytest.mark.parametrize("decimal_separator", [".", ","])
858+
@pytest.mark.parametrize("null_value", [None, np.nan], ids=["none", "nan"])
859+
def test_csv_export_duplicate_labels_preserve_mixed_types(
860+
decimal_separator: str,
861+
null_value: Any,
862+
) -> None:
863+
"""Duplicate labels preserve exact numbers, nulls, bools and formula escaping."""
864+
frame = pd.DataFrame(
865+
[
866+
[Decimal("-1.2500"), 1.5, True, 7, "=1+2"],
867+
[Decimal("2.5000"), null_value, False, 8, "keep.this"],
868+
],
869+
columns=["value"] * 5,
870+
index=[0, 0],
871+
dtype=object,
872+
)
873+
original = frame.copy(deep=True)
874+
amount = "-1.2500".replace(".", decimal_separator)
875+
number = "1.5".replace(".", decimal_separator)
876+
second_amount = "2.5000".replace(".", decimal_separator)
877+
878+
assert df_to_escaped_csv(
879+
frame, index=False, sep=";", decimal=decimal_separator
880+
) == (
881+
f"value;value;value;value;value\n{amount};{number};True;7;'=1+2\n"
882+
f"{second_amount};;False;8;keep.this\n"
883+
)
884+
pd.testing.assert_frame_equal(frame, original)

0 commit comments

Comments
 (0)