Skip to content

Commit f036b41

Browse files
ENH: Write excel comments, via tooltips (xlsxwriter engine) (pandas-dev#58070)
Co-authored-by: diogomsmiranda <[email protected]>
1 parent d969dd8 commit f036b41

File tree

3 files changed

+26
-0
lines changed

3 files changed

+26
-0
lines changed

pandas/io/excel/_base.py

+3
Original file line numberDiff line numberDiff line change
@@ -1208,6 +1208,7 @@ def book(self) -> _WorkbookT:
12081208
def _write_cells(
12091209
self,
12101210
cells,
1211+
notes,
12111212
sheet_name: str | None = None,
12121213
startrow: int = 0,
12131214
startcol: int = 0,
@@ -1220,6 +1221,8 @@ def _write_cells(
12201221
----------
12211222
cells : generator
12221223
cell of formatted data to save to Excel sheet
1224+
notes : dataframe
1225+
dataframe that holds notes to write
12231226
sheet_name : str, default None
12241227
Name of Excel sheet, if None, then use self.cur_sheet
12251228
startrow : upper left cell row to dump data frame

pandas/io/excel/_xlsxwriter.py

+16
Original file line numberDiff line numberDiff line change
@@ -241,6 +241,7 @@ def _save(self) -> None:
241241
def _write_cells(
242242
self,
243243
cells,
244+
notes,
244245
sheet_name: str | None = None,
245246
startrow: int = 0,
246247
startcol: int = 0,
@@ -258,6 +259,8 @@ def _write_cells(
258259
if validate_freeze_panes(freeze_panes):
259260
wks.freeze_panes(*(freeze_panes))
260261

262+
notes_col = None
263+
261264
for cell in cells:
262265
val, fmt = self._value_with_fmt(cell.val)
263266

@@ -281,4 +284,17 @@ def _write_cells(
281284
style,
282285
)
283286
else:
287+
if notes_col is None:
288+
notes_col = startcol + cell.col
284289
wks.write(startrow + cell.row, startcol + cell.col, val, style)
290+
291+
if notes is None:
292+
return
293+
294+
for row_idx, (_, row) in enumerate(notes.iterrows()):
295+
for col_idx, note in enumerate(row):
296+
wks.write_comment(
297+
row_idx + 1, # first row has columns
298+
col_idx + notes_col, # n columns with indexes
299+
str(note),
300+
)

pandas/io/formats/excel.py

+7
Original file line numberDiff line numberDiff line change
@@ -554,6 +554,9 @@ def __init__(
554554
self.rowcounter = 0
555555
self.na_rep = na_rep
556556
if not isinstance(df, DataFrame):
557+
self.notes = None
558+
if df.tooltips is not None:
559+
self.notes = df.tooltips.tt_data
557560
self.styler = df
558561
self.styler._compute() # calculate applied styles
559562
df = df.data
@@ -880,6 +883,9 @@ def get_formatted_cells(self) -> Iterable[ExcelCell]:
880883
cell.val = self._format_value(cell.val)
881884
yield cell
882885

886+
def get_notes(self) -> Iterable[str]:
887+
yield from self.notes.iterrows()
888+
883889
@doc(storage_options=_shared_docs["storage_options"])
884890
def write(
885891
self,
@@ -941,6 +947,7 @@ def write(
941947
try:
942948
writer._write_cells(
943949
formatted_cells,
950+
self.notes,
944951
sheet_name,
945952
startrow=startrow,
946953
startcol=startcol,

0 commit comments

Comments
 (0)