1. 添加批注
獲取指定行的指定列的單元格,給單元格添加批注
public void setCellComment() {
Row row = sheet.getRow(0);
Iterator<Cell> iterator = row.iterator();
// 遍歷標題行,得到所有列的坐標及列名信息
while (iterator.hasNext()) {
Cell currentCell = iterator.next();
// 列坐標,第幾列
int columnIndex = currentCell.getColumnIndex();
// 列名
String stringCellValue = currentCell.getStringCellValue();
}
Cell cell = row.getCell(0);
Drawing patriarch = sheet.createDrawingPatriarch();
cell.removeCellComment();
ClientAnchor anchor = new XSSFClientAnchor();
anchor.setDx1(0);
anchor.setDx2(0);
anchor.setDy1(0);
anchor.setDy2(0);
anchor.setCol1(cell.getColumnIndex());
anchor.setRow1(cell.getRowIndex());
anchor.setCol2(cell.getColumnIndex() + 2);
anchor.setRow2(cell.getRowIndex() + 2);
// 定義注釋的大小和位置,詳見文檔
Comment comment = patriarch.createCellComment(anchor);
// 設置注釋內容
comment.setString(new XSSFRichTextString("這是測試批注"));
// 設置注釋作者. 當鼠標移動到單元格上是可以在狀態欄中看到該內容.
comment.setAuthor("張三");
cell.setCellComment(comment);
}
2. 給批注單元格添加樣式
public static void setCellStyle(Workbook workbook, Cell cell) {
CellStyle cellStyle = workbook.createCellStyle();
//垂直居中
cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
//水平居中
cellStyle.setAlignment(HorizontalAlignment.CENTER);
// 紅色背景框
cellStyle.setFillForegroundColor(IndexedColors.RED.getIndex());
cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
// 邊框線條樣式
BorderStyle medium = BorderStyle.THIN;
// 邊框線條顏色
short borderColor = IndexedColors.BLACK.getIndex();
// 上下左右邊框全部采用黑色實線
cellStyle.setBorderBottom(medium);
cellStyle.setBottomBorderColor(borderColor);
cellStyle.setBorderLeft(medium);
cellStyle.setLeftBorderColor(borderColor);
cellStyle.setBorderRight(medium);
cellStyle.setRightBorderColor(borderColor);
cellStyle.setBorderTop(medium);
cellStyle.setTopBorderColor(borderColor);
cell.setCellStyle(cellStyle);
}