If you frequently work with Excel data, you have probably noticed the small red triangle in the top-right corner of a cell. That is a comment. Comments are especially useful in scenarios such as team collaboration, data review, and report annotations. However, manually adding comments is inefficient, particularly when batch processing is required.
In this guide, we will demonstrate how to work with Excel comments in Python, covering everything from simple text comments to advanced features like rich text formatting, background images, precise positioning, and automated review workflows.
Use Cases for Excel Comments
In real-world workflows, Excel comments are mainly used for the following purposes:
Data review: Mark abnormal data and explain calculation logic
Team collaboration: Leave suggestions, review notes, or discussion records
Template documentation: Explain field meanings and input rules
Audit trail: Record data sources and processing steps
Visual enhancement: Use image comments for branding or visual indicators
Understanding these use cases helps you decide when to use comments and when to use other approaches, such as a separate explanation sheet.
Environment Setup
Before writing code, prepare your Python environment and install a library for manipulating Excel files. This guide uses Spire.XLS for Python, which allows you to create, read, edit, and save Excel files without requiring Microsoft Excel. It is suitable for server-side reporting, batch data review, and office automation tasks.
1. Install the Python Library
Install Spire.XLS for Python via pip:
pip install spire.xls
Once installed, import the necessary classes in your Python script:
from spire.xls import Workbook, ExcelVersion
Where:
Workbookis used to create or load an Excel workbook.ExcelVersionspecifies the Excel file format when saving, such as.xlsx.For advanced settings such as colors, text rotation, and alignment, you may also need to import classes such as
Color,ExcelColors, andTextRotationType.
2. Prepare Test Files
If an example creates a new workbook, you can run the code directly to generate an Excel file. If the code uses LoadFromFile(), prepare an existing Excel file first, for example:
workbook.LoadFromFile("data.xlsx")
This means the program will read data.xlsx from the same directory as the Python script. If the file is located elsewhere, use a full file path:
workbook.LoadFromFile(r"C:\Users\Administrator\Desktop\data.xlsx")
3. Output File Format
Most examples in this guide save the result like this:
workbook.SaveToFile("output.xlsx", ExcelVersion.Version2013)
Here, ExcelVersion.Version2013 saves the file in the modern .xlsx format, which is suitable for Microsoft Excel 2013 and later. If you need compatibility with older Excel versions, choose another Excel version parameter based on your requirements.
1. Add Comments to Excel in Python
Adding comments is the basic operation for working with Excel comments. The usual workflow is to create or load a workbook, access the target worksheet and cell, and then use the AddComment() method to add a comment object to that cell.
After creating a comment, you can set its text, visibility, size, and rich text formatting.
1.1 Add a Simple Text Comment
from spire.xls import Workbook, ExcelVersion
workbook = Workbook()
sheet = workbook.Worksheets[0]
# Add a comment to cell C1
cell = sheet.Range["C1"]
comment = cell.AddComment()
comment.Text = "This is a simple comment"
# By default, comments are hidden and appear on hover
# To keep the comment visible:
comment.Visible = True
workbook.SaveToFile("simple_comment.xlsx", ExcelVersion.Version2013)
workbook.Dispose()
This is the simplest way to add a comment. In real projects, however, you usually need more control over the content and appearance.
1.2 Add a Comment with Author Information
In team collaboration or data review scenarios, a simple note may not be clear enough. To make comments easier to track, you can include the author, review time, or processing status in the comment text.
Spire.XLS does not require comments to contain a separate author field, so you can organize the content manually, such as using the format Author + newline + comment content.
from spire.xls import Workbook, ExcelVersion
workbook = Workbook()
workbook.LoadFromFile("data.xlsx")
sheet = workbook.Worksheets[0]
# Get the target cell
cell = sheet.Range["C1"]
# Set author and content
author = "John Doe"
text = "This data requires further verification"
comment = cell.AddComment()
comment.Width = 200
comment.Visible = True
# Format: author + newline + content
comment.Text = f"{author}:\n{text}"
# Make the author name bold
font = workbook.CreateFont()
font.FontName = "Tahoma"
font.IsBold = True
comment.RichText.SetFont(0, len(author), font)
workbook.SaveToFile("comment_with_author.xlsx", ExcelVersion.Version2013)
workbook.Dispose()
Why include the author? In a multi-person workflow, it makes it easy to identify who left each note.
2. Format Excel Comments with Rich Text in Python
Plain comments apply the same style to all text. But in some cases, you may need to emphasize key information or distinguish different parts of a comment. This is where rich text comments are useful.
When a comment is long, or when you need to highlight words such as “Warning”, “Reviewed”, or “Pending”, plain text may not be readable enough. You can use rich text formatting to apply different fonts, colors, font sizes, or bold styles to specific text ranges.
The core idea is to set the complete comment text first, and then use RichText.SetFont() to apply a font style to a specified character range.
2.1 Apply Multiple Text Colors in a Comment
The following example shows how to use multiple colors in one comment. In real development, this method is commonly used to distinguish note types, such as using a prominent color for “Attention” or “Warning” and a softer color for the detailed explanation.
from spire.xls import Workbook, ExcelVersion, ExcelColors
workbook = Workbook()
workbook.LoadFromFile("template.xlsx")
sheet = workbook.Worksheets[0]
# Create fonts with different colors
font_orange = workbook.CreateFont()
font_orange.FontName = "Arial"
font_orange.Size = 11
font_orange.KnownColor = ExcelColors.Orange
font_blue = workbook.CreateFont()
font_blue.KnownColor = ExcelColors.LightBlue
font_green = workbook.CreateFont()
font_green.KnownColor = ExcelColors.LightGreen
# Add a comment and set rich text
cell = sheet.Range["B12"]
comment = cell.Comment
comment.RichText.Text = "Attention: This data has been reviewed"
# Apply green to the first part, "Attention:"
comment.RichText.SetFont(0, 10, font_green)
# Apply blue to the remaining text
comment.RichText.SetFont(11, len(comment.RichText.Text) - 11, font_blue)
workbook.SaveToFile("rich_text_comment.xlsx", ExcelVersion.Version2007)
workbook.Dispose()
Expected effect:
Attention:appears in green as a warning or marker.This data has been reviewedappears in blue as informational text.
2.2 Create a Comment with Complex Formatting
from spire.xls import Workbook, ExcelVersion, Color
workbook = Workbook()
sheet = workbook.Worksheets[0]
# Create multiple font styles
font_title = workbook.CreateFont()
font_title.FontName = "Calibri"
font_title.Color = Color.get_Firebrick() # Dark red
font_title.IsBold = True
font_title.Size = 12
font_body = workbook.CreateFont()
font_body.FontName = "Calibri"
font_body.Color = Color.get_Blue()
font_body.Size = 12
# Add a detailed comment
cell = sheet.Range["G5"]
comment = cell.Comment
comment.IsVisible = True
comment.Height = 150
comment.Width = 300
comment.RichText.Text = "Product Description:\nSpire.XLS is an independent Excel component that supports conversion, data processing, charts, and more."
# Apply bold red formatting to the title
comment.RichText.SetFont(0, 20, font_title)
# Apply blue formatting to the body
comment.RichText.SetFont(21, len(comment.RichText.Text) - 21, font_body)
workbook.SaveToFile("formatted_comment.xlsx", ExcelVersion.Version2013)
workbook.Dispose()
Applicable scenarios: Technical documentation, product descriptions, and comments that need a clear information hierarchy.
3. Read and Edit Existing Excel Comments in Python
Besides creating comments, you may also need to read and update existing comments. For example, after a review process, you may need to extract all comment content and generate a review report. Or you may need to update comments in bulk according to new business rules.
To read a comment, access the Comment property of a cell. To edit a comment, modify its Text or RichText content directly.
3.1 Read Comment Content
from spire.xls import Workbook
workbook = Workbook()
workbook.LoadFromFile("with_comments.xlsx")
sheet = workbook.Worksheets[0]
# Read the comment from cell A1
comment_text = sheet.Range["A1"].Comment.Text
print(f"Comment content: {comment_text}")
# If the comment contains rich text, get the RTF content
rich_text = sheet.Range["A2"].Comment.RichText.RtfText
print(f"Rich text format: {rich_text}")
workbook.Dispose()
Use cases:
Extract all comments to generate a review report
Analyze keywords in comments
Export comments to a database
3.2 Read All Comments in Bulk
from spire.xls import Workbook
workbook = Workbook()
workbook.LoadFromFile("reviewed_data.xlsx")
sheet = workbook.Worksheets[0]
# Iterate through all cells that may contain comments
comments_info = []
for row in range(1, sheet.AllocatedRange.RowCount + 1):
for col in range(1, sheet.AllocatedRange.ColumnCount + 1):
cell = sheet.Range[row, col]
if cell.Comment is not None:
info = {
'cell': f"{chr(64+col)}{row}", # For example, "A1"
'author': cell.Comment.Text.split(':')[0] if ':' in cell.Comment.Text else '',
'content': cell.Comment.Text,
'visible': cell.Comment.Visible
}
comments_info.append(info)
# Output all comment information
for info in comments_info:
print(f"Cell {info['cell']}: {info['content']}")
workbook.Dispose()
3.3 Edit Existing Comments
from spire.xls import Workbook, ExcelVersion
workbook = Workbook()
workbook.LoadFromFile("existing_comments.xlsx")
sheet = workbook.Worksheets[0]
# Method 1: Directly modify the first comment
comment = sheet.Comments[0]
comment.Text = "Comment content updated - 2024 review"
# Method 2: Modify the comment in a specific cell
sheet.Range["B5"].Comment.Text = "Data has been corrected"
workbook.SaveToFile("updated_comments.xlsx", ExcelVersion.Version2013)
workbook.Dispose()
4. Delete Excel Comments in Python
Comments are often used for review, explanation, or temporary communication. When a file is ready for final release, archiving, or external sharing, you may need to delete some or all comments to avoid distracting readers or exposing internal review information.
You can delete comments through the sheet.Comments collection, or locate a specific cell first and then remove its comment.
from spire.xls import Workbook, ExcelVersion
workbook = Workbook()
workbook.LoadFromFile("with_comments.xlsx")
sheet = workbook.Worksheets[0]
# Method 1: Delete a specific comment
comments = sheet.Comments
if comments.Count > 0:
comments[1].Remove() # Delete the second comment
# Method 2: Delete all comments
while sheet.Comments.Count > 0:
sheet.Comments[0].Remove()
workbook.SaveToFile("no_comments.xlsx", ExcelVersion.Version2013)
workbook.Dispose()
Practical scenarios:
Remove review comments before publishing the final version
Delete temporary notes before archiving
Delete comments based on conditions, such as keeping only comments from the last month
5. Customize Excel Comments in Python
Basic comments solve the problem of adding explanations. Advanced customization focuses on whether comments are readable, layout-friendly, and suitable for report presentation. In formal reports, template files, or automatically generated review documents, you may need to control comment size, position, visibility, background images, and text direction.
These settings allow comments to become part of the reporting and review workflow rather than simple notes.
5.1 Control Comment Position and Size
The default comment position may not always be ideal. You can control it precisely:
from spire.xls import Workbook, ExcelVersion, CommentVAlignType, CommentHAlignType
workbook = Workbook()
sheet = workbook.Worksheets[0]
# Add a comment
cell = sheet.Range["G5"]
cell.Text = "View comment"
comment = cell.Comment
comment.IsVisible = True
comment.Height = 150 # Height
comment.Width = 300 # Width
# Set absolute position relative to the top-left corner of the worksheet
comment.Top = 20 # 20 pixels from the top
comment.Left = 40 # 40 pixels from the left
# Set text alignment
comment.VAlignment = CommentVAlignType.Center
comment.HAlignment = CommentHAlignType.Justified
comment.RichText.Text = "This is a precisely positioned comment.\nYou can control its size, position, and alignment."
workbook.SaveToFile("positioned_comment.xlsx", ExcelVersion.Version2013)
workbook.Dispose()
Why control the position?
Avoid covering important data
Arrange multiple comments more cleanly
Make comment placement more predictable when printing
5.2 Set a Background Image for a Comment
In addition to text formatting, you can further customize the appearance of comments. For example, in corporate templates or branded reports, you can set an image as the comment background to display a logo, icon, or other visual element.
To do this, load the image as a file stream and apply it to the comment using comment.Fill.CustomPicture().
from spire.xls import Workbook, ExcelVersion
from System.IO import FileStream, FileMode
workbook = Workbook()
sheet = workbook.Worksheets[0]
# Add text to the cell
cell = sheet.Range["C6"]
cell.Text = "Company Logo"
# Add a comment
comment = cell.AddComment()
# Load an image as the background
image_stream = FileStream("logo.png", FileMode.Open)
comment.Fill.CustomPicture(image_stream, "logo.png")
comment.Visible = True
workbook.SaveToFile("comment_with_image.xlsx", ExcelVersion.Version2010)
workbook.Dispose()
Use cases:
Add a company logo to enterprise templates
Use icons to distinguish different comment types
Build branded reporting systems
5.3 Rotate Comment Text
from spire.xls import Workbook, ExcelVersion, TextRotationType
workbook = Workbook()
sheet = workbook.Worksheets[0]
cell = sheet.Range["D10"]
comment = cell.AddComment()
comment.Text = "This text can be rotated"
comment.TextRotation = TextRotationType.LeftToRight
# Other options:
# TextRotationType.RightToLeft
# TextRotationType.TopToBottom
comment.Visible = True
workbook.SaveToFile("rotated_comment.xlsx", ExcelVersion.Version2013)
workbook.Dispose()
Applicable scenarios: Special layout requirements, multilingual documents, and vertical text display.
5.4 Show or Hide Comments
from spire.xls import Workbook, ExcelVersion
workbook = Workbook()
workbook.LoadFromFile("with_comments.xlsx")
sheet = workbook.Worksheets[0]
# Show all comments
for comment in sheet.Comments:
comment.Visible = True
# Or show/hide specific comments
sheet.Range["A1"].Comment.Visible = True
sheet.Range["B2"].Comment.Visible = False # Hide this comment
workbook.SaveToFile("visibility_control.xlsx", ExcelVersion.Version2013)
workbook.Dispose()
Practical applications:
Review mode: Show all comments
Final version: Hide comments without deleting them, preserving history
Before printing: Hide comments to avoid visual clutter
6. Practical Example: Build an Automated Excel Review System
The previous examples covered adding, reading, editing, deleting, and styling comments. Now let us combine these operations in a complete example that simulates a simple data review workflow.
The program reads sales data from a CSV file, writes it to Excel, automatically detects abnormal values based on business rules, and adds comments and background colors to the corresponding cells.
This example is closer to a real-world project and is suitable for report review, data quality checks, and abnormal data marking.
from spire.xls import Workbook, ExcelVersion, Color
import csv
def create_review_report(csv_file: str, output_file: str):
"""
Create an Excel report from a CSV file and automatically add review comments.
"""
workbook = Workbook()
sheet = workbook.Worksheets[0]
sheet.Name = "Sales Data Review"
# Create font styles
font_warning = workbook.CreateFont()
font_warning.Color = Color.get_Red()
font_warning.IsBold = True
font_info = workbook.CreateFont()
font_info.Color = Color.get_Blue()
# Read CSV data
with open(csv_file, 'r', encoding='utf-8') as f:
reader = csv.reader(f)
headers = next(reader)
# Write headers
for col, header in enumerate(headers, 1):
sheet.Range[1, col].Value = header
# Write data and check for anomalies
row_num = 2
for row in reader:
for col, value in enumerate(row, 1):
sheet.Range[row_num, col].Value = value
# Assume the 3rd column is sales amount and check abnormal values
try:
sales = float(row[2])
# If sales amount exceeds 10000, add a warning comment
if sales > 10000:
cell = sheet.Range[row_num, 3]
comment = cell.AddComment()
comment.Text = f"Warning: Sales amount {sales:.2f} exceeds the normal range\nPlease verify data accuracy"
comment.Width = 250
comment.Visible = True
# Apply warning style
comment.RichText.SetFont(0, 7, font_warning)
comment.RichText.SetFont(8, len(comment.Text), font_info)
# Highlight the cell
cell.Style.Color = Color.get_LightYellow()
except (ValueError, IndexError):
pass
row_num += 1
# Auto-fit columns
sheet.AllocatedRange.AutoFitColumns()
# Add an instruction comment
title_cell = sheet.Range["A1"]
title_comment = title_cell.AddComment()
title_comment.Text = "Review Notes:\n- Red comments: abnormal data to verify\n- Yellow background: marked high values\n- Remove these comments after review"
title_comment.Width = 300
title_comment.Height = 150
title_comment.Visible = True
workbook.SaveToFile(output_file, ExcelVersion.Version2013)
workbook.Dispose()
print(f"Review report generated: {output_file}")
# Usage example
create_review_report("sales_data.csv", "sales_review.xlsx")
This example demonstrates:
Automatic detection: Identify anomalies based on business rules
Smart comments: Provide different messages for different situations
Visual cues: Use both colors and comments to mark important cells
Traceability: Keep review records in the workbook
7. Practical Tips for Working with Excel Comments
1. When Should You Use Comments?
Use comments for:
Temporary review suggestions
Cell-level explanations
Notes that need to be shown or hidden
Avoid comments for:
Long explanations, which are better placed in a separate worksheet
Permanent important information, which should be placed in cells, headers, or footers
Structured data, which should be stored in additional columns
2. Performance Considerations
A large number of comments, such as hundreds or more, may slow down file opening.
Rich text comments take more space than plain text comments.
Comments with background images can significantly increase file size.
Suggestions:
Clean up unnecessary comments regularly.
Remove review comments before publishing the final version.
Use a separate worksheet for large amounts of explanatory content.
3. Best Practices for Excel Comments
✅ Do:
Keep comments concise and clear.
Include the author and timestamp.
Make important comments visible.
Review and clean up comments regularly.
❌ Do not:
Store important data in comments.
Write overly long comments. If a comment exceeds around 100 words, consider another approach.
Forget to remove temporary comments.
Include sensitive information in comments, as comments are easy to overlook and may lead to accidental disclosure.
4. Comments vs. Other Solutions
| Requirement | Recommended Solution | Reason |
|---|---|---|
| Cell-level explanation | Comment | Does not occupy cell space |
| Long documentation | Separate worksheet | Easier to read and manage |
| Data validation prompt | Data validation | Provides instant input guidance |
| Formula explanation | Named ranges + description | More structured |
| Version history | Separate history worksheet | Easier to track |
8. Frequently Asked Questions
Q1: How can I export all comments in bulk?
A: Iterate through all cells, extract comment content, and save it to a text file or database:
comments_export = []
for row in range(1, max_row + 1):
for col in range(1, max_col + 1):
cell = sheet.Range[row, col]
if cell.Comment:
comments_export.append({
'location': f"{chr(64+col)}{row}",
'text': cell.Comment.Text
})
# Save to CSV or database
Q2: Do comments affect printing?
A: By default, comments are not printed. If you need to print them:
In Excel: Go to Page Layout > Print Titles and set comments to At end of sheet.
In code: Configure page setup options depending on the library version and available APIs.
Q3: Can comments be protected from editing?
A: You can protect the worksheet, but this also locks cells. A better approach is to:
Remove comments after the review is complete.
Or copy comment content to a protected worksheet.
Conclusion
Comments are an underrated Excel feature. Used properly, they can greatly improve collaboration efficiency and data quality. Through the examples in this article, you should now understand how to:
Perform basic operations: Add, read, edit, and delete comments
Apply rich text formatting: Use multiple colors, fonts, and hierarchical formatting
Customize comments: Control position, add background images, and rotate text
Build automation workflows: Process comments in batches, mark data intelligently, and create review systems
Follow best practices: Know when to use comments, how to use them, and what to avoid
Core principle: Comments should help readers understand data, not store data. Keep comments concise, relevant, and regularly cleaned up so they can provide real value.
I hope this guide helps with your Excel automation work.
Top comments (0)