1 | initial version |
To obtain a comment object from an Excel cell using C#, you can follow these steps:
Open the Excel workbook using the Workbook
class in the Microsoft.Office.Interop.Excel
namespace.
Select the worksheet in which the target cell is located using the Worksheet
property of the Workbook
object.
Access the target cell using the Range
property of the Worksheet
object, and then use the Comment
property of the Range
object to get the comment attached to the cell.
You can then read or modify the properties of the comment object (e.g. Comment.Text
to get the comment text, Comment.Author
to get the author of the comment, Comment.Visible
to get or set the visibility of the comment, etc.).
Here is some sample code to illustrate the process:
using Microsoft.Office.Interop.Excel;
// Open the Excel workbook
Workbook workbook = new Application().Workbooks.Open(@"C:\example.xlsx");
// Select the worksheet
Worksheet worksheet = workbook.Worksheets["Sheet1"];
// Get the comment from cell A1
Range cellRange = worksheet.Range["A1"];
Comment comment = cellRange.Comment;
// Display the comment text and author
if (comment != null)
{
Console.WriteLine("Comment text: " + comment.Text);
Console.WriteLine("Comment author: " + comment.Author);
}
else
{
Console.WriteLine("There is no comment in cell A1.");
}
// Modify the comment properties (e.g. set the visibility to false)
if (comment != null)
{
comment.Visible = false;
}
// Close the workbook
workbook.Close();