本文将介绍如何使用 Spire.XLS for Java给Excel文档添加批注以及如何读取Excel文档的现有批注的内容。
添加批注
import com.spire.xls.*;
public class InsertComments {
public static void main(String[] args){
//新建Excel文档
Workbook workbook = new Workbook();
//获取第一张工作表
Worksheet sheet = workbook.getWorksheets().get(0);
//创建字体
ExcelFont font = workbook.createFont();
font.setFontName("Arial");
font.setSize(11);
font.setKnownColor(ExcelColors.Orange);
ExcelFont fontBlue = workbook.createFont();
fontBlue.setKnownColor(ExcelColors.LightBlue);
ExcelFont fontGreen = workbook.createFont();
fontGreen.setKnownColor(ExcelColors.LightGreen);
//给指定的Excel单元格添加普通批注
CellRange range = sheet.getCellRange("A1");
range.setText("Spire.XLS");
range.getComment().setText("Excel文档处理组件");
range.autoFitColumns();
//给指定的Excel单元格添加富文本批注
range = sheet.getCellRange("A2");
range.setText("Spire.XLS");
range.getRichText().setFont(0, 8, font);
range.autoFitColumns();
range.getComment().getRichText().setText("Excel文档处理组件");
range.getComment().getRichText().setFont(0, 4, fontGreen);
range.getComment().getRichText().setFont(5, 6, fontBlue);
//保存结果文档
workbook.saveToFile("AddComments.xlsx", ExcelVersion.Version2013);
}
}
普通批注:
富文本批注:
读取批注
import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;
public class ReadComments {
public static void main(String[] args){
//加载Excel文档
Workbook workbook = new Workbook();
workbook.loadFromFile("AddComments.xlsx");
//获取第一张工作表
Worksheet sheet = workbook.getWorksheets().get(0);
//打印单元格A1、A2的批注内容
System.out.println("A1 Comment = " + sheet.getCellRange("A1").getComment().getText());
System.out.println("A2 Comment = " + sheet.getCellRange("A2").getComment().getRichText().getRtfText());
}
}