diff --git a/doc/source/whatsnew/v1.5.0.rst b/doc/source/whatsnew/v1.5.0.rst index 5891eeea98cbb..9fc77a7aaa126 100644 --- a/doc/source/whatsnew/v1.5.0.rst +++ b/doc/source/whatsnew/v1.5.0.rst @@ -872,6 +872,7 @@ I/O - Bug in :func:`read_sas` returned ``None`` rather than an empty DataFrame for SAS7BDAT files with zero rows (:issue:`18198`) - Bug in :class:`StataWriter` where value labels were always written with default encoding (:issue:`46750`) - Bug in :class:`StataWriterUTF8` where some valid characters were removed from variable names (:issue:`47276`) +- Bug in :meth:`DataFrame.to_excel` when writing an empty dataframe with :class:`MultiIndex` (:issue:`19543`) Period ^^^^^^ diff --git a/pandas/io/formats/excel.py b/pandas/io/formats/excel.py index d0fea32cafe26..effb0652aa2d3 100644 --- a/pandas/io/formats/excel.py +++ b/pandas/io/formats/excel.py @@ -634,7 +634,7 @@ def _format_header_regular(self) -> Iterable[ExcelCell]: if self.index: coloffset = 1 if isinstance(self.df.index, MultiIndex): - coloffset = len(self.df.index[0]) + coloffset = len(self.df.index.names) colnames = self.columns if self._has_aliases: diff --git a/pandas/tests/io/excel/test_writers.py b/pandas/tests/io/excel/test_writers.py index 42483645d9fc3..ba6366b71d854 100644 --- a/pandas/tests/io/excel/test_writers.py +++ b/pandas/tests/io/excel/test_writers.py @@ -838,6 +838,19 @@ def test_to_excel_multiindex_no_write_index(self, path): # Test that it is the same as the initial frame. tm.assert_frame_equal(frame1, frame3) + def test_to_excel_empty_multiindex(self, path): + # GH 19543. + expected = DataFrame([], columns=[0, 1, 2]) + + df = DataFrame([], index=MultiIndex.from_tuples([], names=[0, 1]), columns=[2]) + df.to_excel(path, "test1") + + with ExcelFile(path) as reader: + result = pd.read_excel(reader, sheet_name="test1") + tm.assert_frame_equal( + result, expected, check_index_type=False, check_dtype=False + ) + def test_to_excel_float_format(self, path): df = DataFrame( [[0.123456, 0.234567, 0.567567], [12.32112, 123123.2, 321321.2]],