poi依賴:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
添加背景色:
依次創建工作表--工作簿--行--單元格
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("sheet1");
XSSFRow row = sheet.createRow(0);
XSSFCell cell = row.createCell(i);
創建樣式對象,並設置背景(注意是foreground,不是background,兩者是相反的)黃色,且是實心
XSSFCellStyle cellStyle = workbook.createCellStyle();
cellStyle.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
設置樣式
cell.setCellStyle(cellStyle);
添加批注:
依次創建工作表--工作簿--行--單元格
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("sheet1");
XSSFRow row = sheet.createRow(0);
XSSFCell cell = row.createCell(i);
依次創建畫布--錨點--批注--設置批注內容
XSSFDrawing drawingPatriarch = sheet.createDrawingPatriarch(); //畫布(注意批注是一種圖形,所以要用畫布)
XSSFClientAnchor xSSFClientAnchor = new XSSFClientAnchor(0, 0, 0, 0, 1, 0, 4, 4); //錨點,確定批注的位置(8個參數中:后4個是根據單元格定位,前4個是根據后4個定好的位置再按像素微調)
XSSFComment cellComment = drawingPatriarch.createCellComment(xSSFClientAnchor); // 在錨點位置創建批注
cellComment.setString("批注內容"); // 設置批注內容
設置樣式
cell.setCellStyle(cellStyle);
特別注意: 每個批注都是一個獨立的畫布,所以如果多個單元格都需要批注時,要為每一個批注都創建一套"畫布,錨點,批注".
添加下拉值:
DataValidationHelper dataValidationHelper = sheet.getDataValidationHelper();
// 構造帶下拉列表約束的下拉框
DataValidationConstraint constraint = dataValidationHelper.createExplicitListConstraint(new String[]{"A","B","C","D"}); // 下拉值:A,B,C,D
// 划定需要下拉的區域
CellRangeAddressList cellRangeAddressList = new CellRangeAddressList(0, 1000, 0, 0); // 0-1000行,0-0列
// 綁定下拉框和區域,構造數據驗證對象
DataValidation validation = dataValidationHelper.createValidation(constraint, cellRangeAddressList);
// 為sheet添加此驗證對象
sheet.addValidationData(validation);
總結:
1. 使用POI可以在Java代碼中操作Excel任意功能,同理在WORD,PPT中也可用
2. 批注需要一個獨立的畫布,所以對於每個批注都要創建一個畫布