Skip to content

Commit 5b7390b

Browse files
ENH: Add support for writing excel comments (openpyxl engine) (pandas-dev#58070)
Co-authored-by: diogomsmiranda <[email protected]>
1 parent fc3b368 commit 5b7390b

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

pandas/io/excel/_openpyxl.py

+20
Original file line numberDiff line numberDiff line change
@@ -443,11 +443,14 @@ def _convert_to_protection(cls, protection_dict):
443443
def _write_cells(
444444
self,
445445
cells,
446+
notes,
446447
sheet_name: str | None = None,
447448
startrow: int = 0,
448449
startcol: int = 0,
449450
freeze_panes: tuple[int, int] | None = None,
450451
) -> None:
452+
from openpyxl.comments import Comment
453+
451454
# Write the frame cells using openpyxl.
452455
sheet_name = self._get_sheet_name(sheet_name)
453456

@@ -484,7 +487,11 @@ def _write_cells(
484487
row=freeze_panes[0] + 1, column=freeze_panes[1] + 1
485488
)
486489

490+
notes_col = None
491+
487492
for cell in cells:
493+
if notes_col is None:
494+
notes_col = startcol + cell.col + 1
488495
xcell = wks.cell(
489496
row=startrow + cell.row + 1, column=startcol + cell.col + 1
490497
)
@@ -530,6 +537,19 @@ def _write_cells(
530537
for k, v in style_kwargs.items():
531538
setattr(xcell, k, v)
532539

540+
if notes is None:
541+
return
542+
543+
for row_idx, (_, row) in enumerate(notes.iterrows()):
544+
for col_idx, note in enumerate(row):
545+
xcell = wks.cell(
546+
row=row_idx + 2, # openpyxl starts counting at 1, not 0
547+
column=col_idx + notes_col,
548+
)
549+
if note:
550+
comment = Comment(note, "")
551+
xcell.comment = comment
552+
533553

534554
class OpenpyxlReader(BaseExcelReader["Workbook"]):
535555
@doc(storage_options=_shared_docs["storage_options"])

0 commit comments

Comments
 (0)