Pandas version checks

  • [X] I have checked that this issue has not already been reported.

  • [X] I have confirmed this bug exists on the latest version of pandas.

  • [X] I have confirmed this bug exists on the main branch of pandas.

Reproducible Example

import pandas as pd

# Crate an empty DataFrame with MultiIndex
index = pd.MultiIndex(levels=4*[[]], codes=4*[[]], names=['a', 'b', 'c', 'd'])
df = pd.DataFrame(
    index=index, columns=['A']
)

# Add 4 rows to the DataFrame
for k in range(2):
    for l in range(2):
        df.loc[(0,0,k,l)] = 1

# Write to ods file
df.to_excel('DataFrame.ods')

Issue Description

When opening the DataFrame.ods file created by the script (using LibreOffice 7.3.7.2 30(Build:2)) the cells are not merged correctly. The 'a' column spans 0 columns, the 'b' column has the correct span and the 'c' and 'd' columns are merged together. Similar things happen on the rows, where in the 'c' column we have merged rows 2-3 (as expected) but then the second value merges together rows 4-7.

Expected Behavior

No columns should be merged together (and no column should have a span of 0). The 'c' column should merge together rows 2-3 and rows 4-5.

The problem seems to be in pandas/io/formats/excel.py, in ExcelFormatter._format_hierarchical_rows. In the code:

if span_val > 1:
    mergestart = self.rowcounter + i + span_val - 1
    mergeend = gcolidx

mergestart and mergeend are the values assigned to the row and column span. gcolidx keeps the index of the column, which causes the strange behaviour of 'a' spanning 0 columns, 'b' spanning 1 column, 'c' spanning 2 columns, etc... The same problem applies to the rows.

Installed Versions

/home/user/anaconda3/envs/Pandas/lib/python3.10/site-packages/_distutils_hack/__init__.py:33: UserWarning: Setuptools is replacing distutils. warnings.warn("Setuptools is replacing distutils.") INSTALLED VERSIONS ------------------ commit : 91111fd99898d9dcaa6bf6bedb662db4108da6e6 python : 3.10.8.final.0 python-bits : 64 OS : Linux OS-release : 5.15.0-53-generic Version : #59-Ubuntu SMP Mon Oct 17 18:53:30 UTC 2022 machine : x86_64 processor : x86_64 byteorder : little LC_ALL : None LANG : en_GB.UTF-8 LOCALE : en_GB.UTF-8 pandas : 1.5.1 numpy : 1.23.4 pytz : 2022.1 dateutil : 2.8.2 setuptools : 65.5.0 pip : 22.2.2 Cython : 0.29.32 pytest : None hypothesis : None sphinx : None blosc : None feather : None xlsxwriter : None lxml.etree : None html5lib : None pymysql : None psycopg2 : None jinja2 : None IPython : None pandas_datareader: None bs4 : None bottleneck : 1.3.5 brotli : None fastparquet : None fsspec : None gcsfs : None matplotlib : None numba : None numexpr : 2.8.3 odfpy : None openpyxl : None pandas_gbq : None pyarrow : None pyreadstat : None pyxlsb : None s3fs : None scipy : None snappy : None sqlalchemy : None tables : None tabulate : None xarray : None xlrd : None xlwt : None zstandard : None tzdata : None

Comment From: vamsi-verma-s

Hi @Gaussian-art , I think currently writing to .ods files is not supported.

Comment From: rhshadrach

@Gaussian-art: thanks for the report! Confirmed on main, further investigations and PRs to fix are welcome.

@vamsi-verma-s: Looks like writing support was added but not updated in the docs (see #32911). Would you be able to open a new issue for fixing the documentation there?

Comment From: vamsi-verma-s

Hi @rhshadrach , created issue for doc update - https://github.com/pandas-dev/pandas/issues/49790 .

Comment From: asishm

diff --git a/pandas/io/excel/_odswriter.py b/pandas/io/excel/_odswriter.py
index 7c90178226..379f1b7271 100644
--- a/pandas/io/excel/_odswriter.py
+++ b/pandas/io/excel/_odswriter.py
@@ -176,8 +176,8 @@ class ODSWriter(ExcelWriter):
         if style_name is not None:
             attributes["stylename"] = style_name
         if cell.mergestart is not None and cell.mergeend is not None:
-            attributes["numberrowsspanned"] = max(1, cell.mergestart)
-            attributes["numbercolumnsspanned"] = cell.mergeend
+            attributes["numberrowsspanned"] = cell.mergestart - cell.row + 1
+            attributes["numbercolumnsspanned"] = cell.mergeend - cell.col + 1
         return attributes

     def _make_table_cell(self, cell) -> tuple[object, Any]:

This patch seems to fix the issue - the mergestart and mergeend attributes (see usage in the xlsxwriter.py) are the cell coordinates of the end cell of the cell-merge.

I can't think of a way to add this to a test since reading the generated ods file either way retuns the same dataframe (and I don't want to go down the rabbit hole of inspecting the generated xmls)

Comment From: rhshadrach

@asishm - instead of inspecting the xml, can we use the odf package (not the ODFReader class that's in pandas) to read the excel file? Are you able to discern merged vs non-merged cells with this?

Comment From: asishm

@rhshadrach It should be possible - but I haven't looked too much into it. The main "blocker" is that odfpy doesn't expose an easy way to access a cell by coordinates - which would mean there would be re-use of logic defined in ODFReader to test this