Skip to content

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
3 tasks done
rogerbalsach opened this issue Nov 18, 2022 · 6 comments
Open
3 tasks done
Labels
Bug IO Excel read_excel, to_excel MultiIndex

Comments

@rogerbalsach
Copy link

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

@rogerbalsach rogerbalsach added Bug Needs Triage Issue that has not been reviewed by a pandas team member labels Nov 18, 2022
@vamsi-verma-s
Copy link
Contributor

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

@rhshadrach rhshadrach added IO Excel read_excel, to_excel Indexing Related to indexing on series/frames, not to indexes themselves MultiIndex and removed Indexing Related to indexing on series/frames, not to indexes themselves labels Nov 19, 2022
@rhshadrach
Copy link
Member

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

@rhshadrach rhshadrach removed the Needs Triage Issue that has not been reviewed by a pandas team member label Nov 19, 2022
@vamsi-verma-s
Copy link
Contributor

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

@asishm
Copy link
Contributor

asishm commented Nov 19, 2022

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
Copy link
Member

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

@asishm
Copy link
Contributor

asishm commented Dec 18, 2022

@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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Bug IO Excel read_excel, to_excel MultiIndex
Projects
None yet
Development

No branches or pull requests

4 participants