Maven Configuration
Include the necessary repository and dependency in your pom.xml to integrate the library:
<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>http://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.xls.free</artifactId>
<version>2.2.0</version>
</dependency>
</dependencies>Inserting Comments with Rich Text
Create a workbook, access a cell, and attach an annotation with customized font colors for specific character ranges.
import com.spire.xls.*;
public class ExcelAnnotationInserter {
public static void main(String[] args) {
Workbook doc = new Workbook();
Worksheet firstSheet = doc.getWorksheets().get(0);
firstSheet.setName("Annotations");
CellRange headerCell = firstSheet.getCellRange(1, 1);
headerCell.setValue("Review Status:");
CellRange targetCell = firstSheet.getCellRange(5, 1);
targetCell.setValue("Pending");
targetCell.getComment().setText("Approval needed\nCheck the figures.");
targetCell.getComment().setVisible(true);
targetCell.getComment().setHeight(120);
ExcelFont roseFont = doc.createFont();
roseFont.setKnownColor(ExcelColors.Rose);
ExcelFont lavenderFont = doc.createFont();
lavenderFont.setKnownColor(ExcelColors.Lavender);
targetCell.getComment().getRichText().setFont(0, 1, roseFont);
targetCell.getComment().getRichText().setFont(2, 3, lavenderFont);
targetCell.getComment().getRichText().setFont(4, 5, roseFont);
doc.saveToFile("AnnotationsOutput.xlsx", ExcelVersion.Version2013);
}
}Retrieving Comment Text
Load an existing spreadsheet to extract and display the textual content of all annotations within a worksheet, or target a specific cell's note.
import com.spire.xls.*;
public class ExcelCommentReader {
public static void main(String[] args) {
Workbook doc = new Workbook();
doc.loadFromFile("AnnotationsOutput.xlsx");
Worksheet ws = doc.getWorksheets().get(0);
for(int idx = 0; idx < ws.getComments().getCount(); idx++) {
String noteContent = ws.getComments().get(idx).getText();
System.out.println(noteContent);
}
// Fetch annotation from a designated cell
// String specificNote = ws.getCellRange(5, 1).getComment().getText();
// System.out.println(specificNote);
}
}Erasing Comments
Remove existing annotations either by iterating through the entire collection safely or by pinpointing the exact cell reference.
import com.spire.xls.*;
public class ExcelAnnotationRemover {
public static void main(String[] args) {
Workbook doc = new Workbook();
doc.loadFromFile("AnnotationsOutput.xlsx");
Worksheet ws = doc.getWorksheets().get(0);
// Erase all annotations from the worksheet safely using reverse iteration
for(int idx = ws.getComments().getCount() - 1; idx >= 0; idx--) {
ws.getComments().get(idx).remove();
}
// Alternatively, remove the annotation tied to a precise cell
// ws.getCellRange(5, 1).getComment().remove();
doc.saveToFile("ClearedAnnotations.xlsx", ExcelVersion.Version2013);
}
}