之前我们介绍了如何插入和读取Excel文本批注,该文将介绍如何使用Spire.XLS for Java给Excel文档添加图片批注。
import com.spire.xls.*;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
public class Test {
public static void main(String[] args)throws IOException {
//加载示例文档
Workbook workbook = new Workbook();
workbook.loadFromFile("Sample.xlsx");
//获取第一个工作表
Worksheet sheet = workbook.getWorksheets().get(0);
//设置字体
ExcelFont font = workbook.createFont();
font.setFontName("Arial");
font.setSize(11);
font.setKnownColor(ExcelColors.Orange);
CellRange range = sheet.getCellRange("D1");
//添加批注
ExcelComment comment = range.addComment();
//加载图片
BufferedImage bufferedImage = ImageIO.read(new File("Logo.jpg"));
//使用图片填充批注
comment.getFill().customPicture(bufferedImage, "Logo.jpg");
//设置批注高度和宽度
comment.setHeight(bufferedImage.getHeight());
comment.setWidth(bufferedImage.getWidth());
//设置批注可见
comment.setVisible(true);
//保存文档
workbook.saveToFile("output/setimageComment.xlsx", ExcelVersion.Version2013);
}
}
效果图: