Skip to content

Commit bb42fc0

Browse files
luke396mroeschke
andauthored
ENH: Add check for character limit (#57103)
Co-authored-by: Matthew Roeschke <[email protected]>
1 parent d9f9e12 commit bb42fc0

File tree

4 files changed

+26
-2
lines changed

4 files changed

+26
-2
lines changed

doc/source/whatsnew/v3.0.0.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ enhancement2
2828

2929
Other enhancements
3030
^^^^^^^^^^^^^^^^^^
31-
-
31+
- :func:`DataFrame.to_excel` now raises an ``UserWarning`` when the character count in a cell exceeds Excel's limitation of 32767 characters (:issue:`56954`)
3232
-
3333

3434
.. ---------------------------------------------------------------------------

pandas/core/generic.py

+4
Original file line numberDiff line numberDiff line change
@@ -2334,6 +2334,10 @@ def to_excel(
23342334
Once a workbook has been saved it is not possible to write further
23352335
data without rewriting the whole workbook.
23362336
2337+
pandas will check the number of rows, columns,
2338+
and cell character count does not exceed Excel's limitations.
2339+
All other limitations must be checked by the user.
2340+
23372341
Examples
23382342
--------
23392343

pandas/io/excel/_base.py

+9-1
Original file line numberDiff line numberDiff line change
@@ -1326,7 +1326,15 @@ def _value_with_fmt(
13261326
fmt = "0"
13271327
else:
13281328
val = str(val)
1329-
1329+
# GH#56954
1330+
# Excel's limitation on cell contents is 32767 characters
1331+
# xref https://support.microsoft.com/en-au/office/excel-specifications-and-limits-1672b34d-7043-467e-8e27-269d656771c3
1332+
if len(val) > 32767:
1333+
warnings.warn(
1334+
"Cell contents too long, truncated to 32767 characters",
1335+
UserWarning,
1336+
stacklevel=find_stack_level(),
1337+
)
13301338
return val, fmt
13311339

13321340
@classmethod

pandas/tests/io/excel/test_writers.py

+12
Original file line numberDiff line numberDiff line change
@@ -1385,6 +1385,18 @@ def test_to_excel_empty_frame(self, engine, ext):
13851385
expected = DataFrame()
13861386
tm.assert_frame_equal(result, expected)
13871387

1388+
def test_to_excel_raising_warning_when_cell_character_exceed_limit(
1389+
self, path, engine
1390+
):
1391+
# GH#56954
1392+
df = DataFrame({"A": ["a" * 32768]})
1393+
msg = "Cell contents too long, truncated to 32767 characters"
1394+
with tm.assert_produces_warning(
1395+
UserWarning, match=msg, raise_on_extra_warnings=False
1396+
):
1397+
buf = BytesIO()
1398+
df.to_excel(buf)
1399+
13881400

13891401
class TestExcelWriterEngineTests:
13901402
@pytest.mark.parametrize(

0 commit comments

Comments
 (0)