BUG: Merging cells doesn't work when writting MultiIndex to .ods file

This issue has been created since 2022-11-18.

Pandas version checks

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

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

  • 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 : 91111fd
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

vamsi-verma-s wrote this answer on 2022-11-18

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

rhshadrach wrote this answer on 2022-11-19

@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?

vamsi-verma-s wrote this answer on 2022-11-19

Hi @rhshadrach , created issue for doc update - #49790 .

asishm wrote this answer on 2022-11-19
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)

rhshadrach wrote this answer on 2022-11-30

@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?

More Details About Repo
Owner Name pandas-dev
Repo Name pandas
Full Name pandas-dev/pandas
Language Python
Created Date 2010-08-24
Updated Date 2022-12-07
Star Count 36164
Watcher Count 1118
Fork Count 15472
Issue Count 3683

YOU MAY BE INTERESTED

Issue Title Created Date Comment Count Updated Date
`requestId` cannot be a requirement for Response Objects 4 2022-06-13 2022-11-09
How the admin of CAs are created in the README example? 2 2022-03-11 2022-10-05
Invalid document when html contains images and existing headers/footers contain images 0 2022-04-25 2022-10-22
Calling MagicImageProcessor.ProcessImage() a second time results in a COM error 4 2020-06-02 2022-11-11
no `cell_specimen_ids` for LearningmFISHTask1A dataset even though cell matching has been run 0 2022-03-15 2022-07-24
Bulk Inserts of Dictionary 3 2022-02-10 2022-09-26
Nextjs SSR build fails with [ERROR]: BadRequest: null 1 2022-06-03 2022-11-03
Cognito login works on local environment but does not work when built on amplify hosting 2 2022-06-03 2022-09-17
Binary .local/bin/gitlint missing after update from 0.16.0 to 0.17.0 15 2021-11-29 2022-11-22
Add REQUESTS_CA_BUNDLE environment variable to image 0 2022-08-30 2022-12-04
Acquistion dump memory 1 2022-01-25 2022-10-02
[SETUP-BUG] localhost refused to connect on GCP notebook 11 2021-12-10 2022-10-02
Laravel 9 - xdebug infinite loop 2 2022-02-13 2022-07-10
batch_size参数体现 1 2020-12-14 2022-01-16
没有seq.data 2 2021-02-10 2022-01-16
Submission Attachment overflows content box 0 2021-11-04 2022-10-01
Support for LibreWolf? 0 2022-02-15 2022-11-12
Hopping on successful event for Freq1 and wait time for Freq2 8 2021-10-20 2022-10-31
Warn about missing dependency (was: Nothing sent with compose method "markdown") 13 2022-02-23 2022-11-27
Set forcesig when using YubiKey as SmartCard 1 2022-01-02 2022-11-26
Error message when using "generic" in a rule configuration with multiple languages is unclear 1 2022-02-17 2022-11-05
Basic command line tool for multisheller? 2 2021-10-26 2022-12-01
Changes to Contour package for new namespace-scoped Role (in Contour v1.21.0) 2 2022-02-10 2022-10-21
Freezing at 100% CPU after some time 17 2022-03-08 2022-12-05
resetting the manifest 2 2022-08-10 2022-09-09
Set Table size 2 2021-07-01 2022-01-16
[Pengguna] Grup Pengguna 2 2021-12-08 2022-09-10
inexact results with pandas 4 2022-10-20 2022-12-02
Question: How to find make command on Windows? 3 2021-07-26 2022-11-27
Add Sorting Options? 0 2022-09-01 2022-11-22
TSLocationManager/TSLocationManager.h' and Tsbackgroundfetch/tsbackgroundfetch.h' file not found when IOS app build in Xcode 9 2021-05-31 2022-10-31
`websubhub:Service` will not complete the subscription verification process if `onSubscription` remote method is not implemented 3 2021-12-20 2022-11-29
FEniCS is not working 4 2021-02-22 2022-11-26
[email protected]: hash check failed 1 2022-09-02 2022-11-29
Improve migrations configuration: use 'folder=>ns' instead of 'ns=>folder' 1 2021-03-22 2022-10-19
Add explicit bounds checks for `JsonGenerator` methods that take `byte[]`/`char[]`/String-with-offsets input 0 2022-08-13 2022-11-28
Feature: Allow more extensive string manipulation in `format` 1 2021-09-28 2022-11-13
[Cloud Foundry]: Redirect routing traffic for /design/thinking from slash-design-router to akamai 0 2022-11-03 2022-11-03
64bit on Raspberry PI 1 2022-02-05 2022-12-01
always staying at confirming "set your name" 11 2021-10-20 2022-11-19
Can we change "Bailys" after whatsup scan QRcode 4 2022-08-10 2022-09-15
[devtools-translate] Portuguese - What's New in DevTools (Chrome 97) 2 2021-11-26 2022-11-20
Use InputStream as data source 6 2015-04-05 2022-11-22
fatal error: can't find local.zeek 5 2021-07-17 2022-11-21
Miri reports dangling pointer for ZST 10 2022-02-08 2022-11-09
Audit log panics if `StreamSessionEvents` called concurrently for the same session 0 2022-08-09 2022-10-31
when will rustdesk support raspbian with desktop version? 4 2022-05-31 2022-11-13
validateAttributes does not validated a nested model relationship 2 2021-12-12 2022-11-25
Blazor - MouseEventArgs.Type property is always null in .NET 6.0 1 2021-12-02 2022-11-22
GDM Now Considers a Yubikey as a Smart Card and Won't Allow Yubikey Authentication for Logins (21.04) 1 2021-08-03 2022-11-23