Apache Poi 将渐变色应用到单元格

Fra*_*zzo 1 java apache excel apache-poi

我一直在网上搜索,但没有找到使用 Apache Poi 将渐变颜色应用于 Excel 表格单元格的真正好的示例。

我发现的例子已经很老了,当前的 Apache Poi 版本中已经不存在这些类了。我目前使用的是 Apache Poi 3.16 版。

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

Axe*_*ter 5

始终无法使用默认的实际apache poi版本设置渐变单元格填充。

因此,我怀疑您找到的代码是针对XSSF( *.xlsx) 的,而对于您找到的代码,只是没有提到此代码需要所有架构的完整 jarooxml-schemas-*.jarpoi-ooxml-full-*.jarfaq-N10025 中提到的类路径中。

以下示例有效,但也需要类路径中所有模式的完整 jar,如faq-N10025 中所述

它首先将图案填充设置设置为CellStyle唯一的填充以从中获取填充索引。然后它获得CTFill在 this 中使用的低级别CellStyle。然后它取消设置图案填充,然后设置渐变填充。

要获取有关如何使用的信息,CTFill需要下载 的源代码ooxml-schemas并执行javadoc. 没有ooxml-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();
 }
}
Run Code Online (Sandbox Code Playgroud)