DEV Community

Allen Yang
Allen Yang

Posted on

Python Excel Comment Guide: Add, Edit, Delete, and Format Comments

Python Excel Comment Guide: Add, Edit, Delete, and Format Comments

When collaborating on Excel data, comments are a common way to communicate. They allow users to attach notes, remarks, or review feedback to cells without altering the original data. Managing Excel comments programmatically enables batch annotation, automatic flagging of data anomalies, and consistent formatting. This article demonstrates how to add, edit, format, and delete comments in Excel files using Python.

Environment Setup

This article uses Spire.XLS for Python to work with Excel files. Install it with the following command:

pip install Spire.XLS
Enter fullscreen mode Exit fullscreen mode

Once installed, import the relevant modules and you are ready to begin.

Adding a Basic Comment

The most straightforward use of comments is attaching a text note to a specific cell. You can set the comment content directly through the Comment property of a cell.

from spire.xls import *
from spire.xls.common import *

workbook = Workbook()
sheet = workbook.Worksheets[0]

# Set cell text
sheet.Range["A1"].Text = "Product A"

# Add a comment
sheet.Range["A1"].Comment.Text = "This product has been discontinued; data is for reference only"

# Make the comment visible
sheet.Range["A1"].Comment.Visible = True

workbook.SaveToFile("BasicComment.xlsx", ExcelVersion.Version2013)
workbook.Dispose()
Enter fullscreen mode Exit fullscreen mode

The Comment.Text property sets plain-text comment content, and the Visible property controls whether the comment is displayed by default. When Visible is set to False, the comment still exists but only appears when the mouse hovers over the cell.

Adding a Comment with Author Information

In multi-person collaboration scenarios, it is useful to distinguish the author of a comment. You can create a comment object using the AddComment() method and then combine the author name with the body text.

from spire.xls import *
from spire.xls.common import *

workbook = Workbook()
workbook.LoadFromFile("DataFile.xlsx")
sheet = workbook.Worksheets[0]

# Get the target cell
cell_range = sheet.Range["C1"]

# Add a comment and set properties
comment = cell_range.AddComment()
comment.Width = 200
comment.Visible = True

# Combine author and body text
author = "Manager Zhang"
text = "This quarter's data has been verified and is ready for publication."
comment.Text = author + ":\n" + text

# Bold the author name
font = workbook.CreateFont()
font.FontName = "Tahoma"
font.KnownColor = ExcelColors.Black
font.IsBold = True
comment.RichText.SetFont(0, len(author), font)

workbook.SaveToFile("CommentWithAuthor.xlsx", ExcelVersion.Version2013)
workbook.Dispose()
Enter fullscreen mode Exit fullscreen mode

The RichText.SetFont() method applies font formatting to a specified range of characters within the comment. The parameters 0 and len(author) define the range from the first character to the end of the author name, so the author name appears in bold, clearly separated from the body text.

Creating Rich Text Comments

When a comment requires different colors or styles to distinguish information hierarchy, you can use rich text formatting.

from spire.xls import *
from spire.xls.common import *

workbook = Workbook()
sheet = workbook.Worksheets[0]

# Create fonts with different colors
font_green = workbook.CreateFont()
font_green.FontName = "Arial"
font_green.Size = 11
font_green.KnownColor = ExcelColors.LightGreen

font_blue = workbook.CreateFont()
font_blue.FontName = "Arial"
font_blue.Size = 11
font_blue.KnownColor = ExcelColors.LightBlue

# Set cell and comment
cell_range = sheet.Range["B12"]
cell_range.Text = "Sales Data"
cell_range.RichText.SetFont(0, 16, font_green)

# Set rich text comment
cell_range.Comment.RichText.Text = "Reviewed: Data is correct"
cell_range.Comment.RichText.SetFont(0, 4, font_green)
cell_range.Comment.RichText.SetFont(5, 9, font_blue)

workbook.SaveToFile("RichTextComment.xlsx", ExcelVersion.Version2013)
workbook.Dispose()
Enter fullscreen mode Exit fullscreen mode

The RichText.SetFont(start_index, end_index, font) method allows you to apply different fonts to different segments of the comment text. This is useful when you need to distinguish status labels from detailed descriptions.

Setting Comment Background Color

By modifying the fill properties of a comment, you can set a background color for the comment box to make it more prominent.

from spire.xls import *
from spire.xls.common import *

workbook = Workbook()
sheet = workbook.Worksheets[0]

# Add a comment
cell_range = sheet.Range["A1"]
cell_range.Comment.Text = "Important: This data requires verification"

# Set font color
font = workbook.CreateFont()
font.FontName = "Arial"
font.Size = 11
font.KnownColor = ExcelColors.Orange
cell_range.Comment.RichText.SetFont(0, len(cell_range.Comment.Text) - 1, font)

# Set comment background color
cell_range.Comment.Fill.FillType = ShapeFillType.SolidColor
cell_range.Comment.Fill.ForeColor = Color.get_SkyBlue()
cell_range.Comment.Visible = True

workbook.SaveToFile("CommentFillColor.xlsx", ExcelVersion.Version2013)
workbook.Dispose()
Enter fullscreen mode Exit fullscreen mode

Once Fill.FillType is set to ShapeFillType.SolidColor, use ForeColor to specify the background color. This approach is useful for marking comment priority or category with color.

Adjusting Comment Position, Size, and Alignment

The position and dimensions of a comment box can be controlled directly through its properties, and text alignment can be set independently.

from spire.xls import *
from spire.xls.common import *

workbook = Workbook()
sheet = workbook.Worksheets[0]

# Add a comment
sheet.Range["G5"].Text = "Data Item"
comment = sheet.Range["G5"].Comment
comment.IsVisible = True
comment.Height = 150
comment.Width = 300

# Set comment text
comment.RichText.Text = "Review note:\nThis data was exported from the system and has passed initial validation."

# Set text rotation
comment.TextRotation = TextRotationType.LeftToRight

# Set comment position (relative to the worksheet)
comment.Top = 20
comment.Left = 40

# Set text alignment
comment.VAlignment = CommentVAlignType.Center
comment.HAlignment = CommentHAlignType.Justified

workbook.SaveToFile("CommentPosition.xlsx", ExcelVersion.Version2013)
workbook.Dispose()
Enter fullscreen mode Exit fullscreen mode

Key property descriptions:

  • Height and Width: Control the pixel dimensions of the comment box
  • Top and Left: Control the position coordinates of the comment box on the worksheet
  • VAlignment: Vertical alignment — options include Top, Center, Bottom
  • HAlignment: Horizontal alignment — options include Left, Center, Right, Justified

Adding an Image Background to a Comment

In addition to solid colors, you can use an image as the background of a comment box, for example to embed a company logo or status icon.

from spire.xls import *
from spire.xls.common import *

workbook = Workbook()
sheet = workbook.Worksheets[0]
sheet.Range["C6"].Text = "Person in Charge"

# Add a comment and set image background
comment = sheet.Range["C6"].AddComment()
image = Stream("Logo.png")
comment.Fill.CustomPicture(image, "logo.png")
comment.Visible = True

workbook.SaveToFile("CommentWithImage.xlsx", ExcelVersion.Version2013)
workbook.Dispose()
Enter fullscreen mode Exit fullscreen mode

The Fill.CustomPicture() method accepts an image stream and an image name parameter. The loaded image is used as the background fill for the comment box.

Reading and Editing Existing Comments

For existing Excel files, you can iterate through the comment collection on a worksheet to read or modify comment content.

from spire.xls import *

workbook = Workbook()
workbook.LoadFromFile("ExistingFile.xlsx")
sheet = workbook.Worksheets[0]

# Read the comment of a specific cell
comment_text = sheet.Range["A1"].Comment.Text
print("Comment:", comment_text)

# Read RTF format of a rich text comment
rtf_text = sheet.Range["A2"].Comment.RichText.RtfText
print("RTF Content:", rtf_text)

workbook.Dispose()
Enter fullscreen mode Exit fullscreen mode

Editing existing comments is equally straightforward — access the comment collection by index and modify its properties:

# Get the first comment and update its content
comment = sheet.Comments[0]
comment.Text = "Comment content updated"
Enter fullscreen mode Exit fullscreen mode

Controlling Comment Visibility

Comments can be individually hidden or shown without deleting them.

from spire.xls import *

workbook = Workbook()
workbook.LoadFromFile("CommentFile.xlsx")
sheet = workbook.Worksheets[0]

# Hide a specific comment
sheet.Comments[1].IsVisible = False

# Show a specific comment
sheet.Comments[2].IsVisible = True

workbook.SaveToFile("CommentVisibility.xlsx", ExcelVersion.Version2013)
workbook.Dispose()
Enter fullscreen mode Exit fullscreen mode

This is useful when you need to toggle comment visibility for different scenarios, such as hiding review comments before printing or presenting.

Deleting Comments

When a comment is no longer needed, you can remove it from the worksheet.

from spire.xls import *

workbook = Workbook()
workbook.LoadFromFile("CommentFile.xlsx")
sheet = workbook.Worksheets[0]

# Delete the second comment
sheet.Comments[1].Remove()

workbook.SaveToFile("CommentRemoved.xlsx", ExcelVersion.Version2013)
workbook.Dispose()
Enter fullscreen mode Exit fullscreen mode

The Remove() method permanently deletes the comment from the worksheet's comment collection. To clear all comments, iterate through the sheet.Comments collection and call Remove() on each one.

Conclusion

This article covered the common operations for managing Excel comments in Python, including:

  1. Adding basic text comments and comments with author information
  2. Using rich text formatting to set comments with different colors and styles
  3. Setting comment background colors and image backgrounds
  4. Adjusting comment position, size, and text alignment
  5. Reading, editing, hiding, and deleting existing comments

These operations cover the main scenarios in comment management. Building on these fundamentals, you can further integrate data validation logic to automatically add comments, or batch-process comments across multiple Excel files to build more comprehensive automation workflows.

Top comments (0)