Apache POI将梯度颜色应用于单元格



我一直在搜索网络,并没有发现使用apache poi将渐变颜色应用于Excel Sheet Cell的真正典范。

我发现的示例很旧,并且当前的Apache POI版本中这些类不再存在。我目前正在使用Apache POI版本3.16。

有人可以指出使用POI库将渐变颜色应用于Excel表所需的步骤。所有提示都将被赞赏。

使用默认的实际 apache poi版本,仍然不可能设置梯度单元格。

因此,我怀疑您发现的代码是针对XSSF*.xlsx),对于您发现的代码,您只是没有提到此代码在类路径中所述的所有schemas ooxml-schemas-*.jarpoi-ooxml-full-*.jar的完整罐子FAQ-N10025。

以下示例有效,但也需要类似于FAQ-N10025中提到的类路径中所有模式的完整罐。

它首先将模式填充设置设置为CellStyle,只是有一些填充以获取填充索引。然后,它获得此CellStyle中使用的低级别CTFill。然后,它将图案填充,然后设置梯度填充。

要获取有关如何使用CTFill的信息,需要下载ooxml-schemas的来源和DO javadocooxml-schemas公众没有API文档。

import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTFill;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTGradientFill;
public class CreateExcelCellGradientFillColor {
 public static void main(String[] args) throws Exception {
  XSSFWorkbook workbook = new XSSFWorkbook();
  Sheet sheet = workbook.createSheet();
  Row row = sheet.createRow(0);
  XSSFCellStyle cellstyle = workbook.createCellStyle();
  //set pattern fill settings only to have some fill to get the fill index from it
  cellstyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
  //get fill index used in this CellStyle
  int fillidx = (int)cellstyle.getCoreXf().getFillId();
  //get the low level CTFill used in this CellStyle
  CTFill ctfill = workbook.getStylesSource().getFillAt(fillidx).getCTFill();
System.out.println(ctfill);
  //unset the pattern fill
  ctfill.unsetPatternFill();
  //now low level set the gradient fill
  byte[] rgb1 = new byte[3];
  rgb1[0] = (byte) 0; // red
  rgb1[1] = (byte) 0; // green
  rgb1[2] = (byte) 255; // blue
  byte[] rgb2 = new byte[3];
  rgb2[0] = (byte) 255; // red
  rgb2[1] = (byte) 255; // green
  rgb2[2] = (byte) 255; // blue
  CTGradientFill ctgradientfill = ctfill.addNewGradientFill();
  ctgradientfill.setDegree(90.0);
  ctgradientfill.addNewStop().setPosition(0.0);
  ctgradientfill.getStopArray(0).addNewColor().setRgb(rgb1);
  ctgradientfill.addNewStop().setPosition(0.5);
  ctgradientfill.getStopArray(1).addNewColor().setRgb(rgb2);
  ctgradientfill.addNewStop().setPosition(1.0);
  ctgradientfill.getStopArray(2).addNewColor().setRgb(rgb1);
System.out.println(ctfill);
  Cell cell = row.createCell(0);
  cell.setCellValue("");
  cell.setCellStyle(cellstyle);
  FileOutputStream out = new FileOutputStream("CreateExcelCellGradientFillColor.xlsx");
  workbook.write(out);
  out.close();
  workbook.close();
 }
}

最新更新