how can i write comments on some cells of excel sheet using pandas

Question:

I didn’t find anything that enable me to write comments on some specific cell while writing excel sheet using panadas.to_excel . Any help is appreciated.

Asked By: Randhawa

||

Answers:

After searching for some time, I think the best way to handle comments or other such properties like color and size of text at cell or sheet level is to use XlsxWriter with pandas.

Here is the link to the some nice examples of using XlsxWriter with pandas:

http://xlsxwriter.readthedocs.org/working_with_pandas.html
Answered By: Randhawa

My reputation is too low to write a comment…

The given link by Randhawa does not provide any information about how to add comments. You can refer to this link https://xlsxwriter.readthedocs.io/working_with_cell_comments.html, which specifies how you can add comments with XlsxWriter.

worksheet.write('A1', 'Hello')
worksheet.write_comment('A1', 'This is a comment')
Answered By: Carsten

(My reputation is also too low to write a comment…)

This is a working example based on the useful web pages linked to by Randhawa and Carsten:

import pandas as pd

# Create a Pandas dataframe
df = pd.DataFrame({"Data": [10, 20, 30, 20, 15, 30, 45]})

# Create a Pandas Excel writer using XlsxWriter as the engine
writer = pd.ExcelWriter("pandas_simple.xlsx", engine="xlsxwriter")

# Convert the dataframe to an XlsxWriter Excel object (sheet)
df.to_excel(writer, sheet_name="Sheet1")

# Get the xlsxwriter object for the sheet where you will write a comment 
workbook = writer.book
worksheet = writer.sheets["Sheet1"]

# Add comment to cell A1 in worksheet ("Sheet1"), set to visible
worksheet.write_comment("A1", "This is a comment", {"visible": True})

# Write the data (sheets) to the workbook
writer.close()
Answered By: mh0w
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.