Skip to content

Commit ddc0525

Browse files
authored
BUG: Error writing an empty DataFrame to an ods file (#45794)
1 parent 9af3bd0 commit ddc0525

File tree

3 files changed

+21
-3
lines changed

3 files changed

+21
-3
lines changed

doc/source/whatsnew/v1.5.0.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -298,7 +298,7 @@ I/O
298298
- Bug in :meth:`DataFrame.info` where a new line at the end of the output is omitted when called on an empty :class:`DataFrame` (:issue:`45494`)
299299
- Bug in :func:`read_csv` not recognizing line break for ``on_bad_lines="warn"`` for ``engine="c"`` (:issue:`41710`)
300300
- Bug in :func:`read_parquet` when ``engine="pyarrow"`` which caused partial write to disk when column of unsupported datatype was passed (:issue:`44914`)
301-
-
301+
- Bug in :func:`DataFrame.to_excel` and :class:`ExcelWriter` would raise when writing an empty DataFrame to a ``.ods`` file (:issue:`45793`)
302302

303303
Period
304304
^^^^^^

pandas/io/excel/_odswriter.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -132,8 +132,9 @@ def write_cells(
132132
tc.addElement(p)
133133

134134
# add all rows to the sheet
135-
for row_nr in range(max(rows.keys()) + 1):
136-
wks.addElement(rows[row_nr])
135+
if len(rows) > 0:
136+
for row_nr in range(max(rows.keys()) + 1):
137+
wks.addElement(rows[row_nr])
137138

138139
def _make_table_cell_attributes(self, cell) -> dict[str, int | str]:
139140
"""Convert cell attributes to OpenDocument attributes

pandas/tests/io/excel/test_writers.py

+17
Original file line numberDiff line numberDiff line change
@@ -1244,6 +1244,23 @@ def test_if_sheet_exists_raises(self, ext):
12441244
with pytest.raises(ValueError, match=re.escape(msg)):
12451245
ExcelWriter(f, if_sheet_exists="replace")
12461246

1247+
def test_excel_writer_empty_frame(self, engine, ext):
1248+
# GH#45793
1249+
with tm.ensure_clean(ext) as path:
1250+
with ExcelWriter(path, engine=engine) as writer:
1251+
DataFrame().to_excel(writer)
1252+
result = pd.read_excel(path)
1253+
expected = DataFrame()
1254+
tm.assert_frame_equal(result, expected)
1255+
1256+
def test_to_excel_empty_frame(self, engine, ext):
1257+
# GH#45793
1258+
with tm.ensure_clean(ext) as path:
1259+
DataFrame().to_excel(path, engine=engine)
1260+
result = pd.read_excel(path)
1261+
expected = DataFrame()
1262+
tm.assert_frame_equal(result, expected)
1263+
12471264

12481265
class TestExcelWriterEngineTests:
12491266
@pytest.mark.parametrize(

0 commit comments

Comments
 (0)