Inserting and Removing Cell Comments in a Worksheet

Adding and Removing Comments on Cells

To add comments to cells:

  1. Open an existing Excel file.
  2. Add a comment to a cell.
  3. Save the file.

To remove the comments, the process is similar, with the exception that the comment is removed.

The code samples below illustrate first how to add a comment and then how to remove a comment with either VSTO or Aspose.Cells for .NET.

Inserting Comments

These code snippets show how to add a comment to a cell first with VSTO (C#, VB) and then with Aspose.Cells for .NET (C#, VB).

Inserting a Comment with VSTO

C#

 .......

using Microsoft.VisualStudio.Tools.Applications.Runtime;

using Excel = Microsoft.Office.Interop.Excel;

using Office = Microsoft.Office.Core;

using System.Reflection;

.......

//Instantiate the Application object.

Excel.Application excelApp = new Excel.ApplicationClass();

//Specify the template excel file path.

string myPath=@"d:\test\Book1.xls";

//Open the excel file.

excelApp.Workbooks.Open(myPath, Missing.Value, Missing.Value,

Missing.Value, Missing.Value,

Missing.Value, Missing.Value,

Missing.Value, Missing.Value,

Missing.Value, Missing.Value,

Missing.Value, Missing.Value,

Missing.Value, Missing.Value);

//Get the A1 cell.

Excel.Range rng1=excelApp.get_Range("A1", Missing.Value);

//Add the comment with text.

rng1.AddComment("This is my comment");

//Save the file.

excelApp.ActiveWorkbook.Save();

//Quit the Application.

excelApp.Quit();

Inserting a Comment with Aspose.Cells for .NET

C#

 .......

using Aspose.Cells;

.......

//Specify the template excel file path.

string myPath=@"d:\test\Book1.xls";

//Instantiate a new Workbook.

//Open the excel file.

Workbook workbook = new Workbook(myPath);

//Add a Comment to A1 cell.

int commentIndex=workbook.Worksheets[0].Comments.Add("A1");

//Accessing the newly added comment

Comment comment=workbook.Worksheets[0].Comments[commentIndex];

//Setting the comment note

comment.Note="This is my comment";

//Save As the excel file.

workbook.Save(@"d:\test\Book1.xls");

Removing Comments

To remove a comment from a cell, use the following lines of code for VSTO (C#, VB) and Aspose.Cells for .NET (C#, VB).

Removing a Comment with VSTO

C#

 //Remove the comment.

rng1.Comment.Delete();    

Removing a Comment with Aspose.Cells for .NET

C#

 //Remove the comment.

workbook.Worksheets[0].Comments.RemoveAt("A1");