gpt4 book ai didi

java - Apache Poi 将渐变颜色应用于单元格

转载 作者:行者123 更新时间:2023-12-02 02:37:23 24 4
gpt4 key购买 nike

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

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

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

最佳答案

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

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

以下示例有效,但还需要类路径中所有架构的完整 jar,如 faq-N10025 中所述。 .

它首先将图案填充设置设置为CellStyle,以便进行一些填充以从中获取填充索引。然后它获取此 CellStyle 中使用的低级 CTFill。然后它取消设置图案填充,然后设置渐变填充。

要获取有关如何使用 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();
}
}

关于java - Apache Poi 将渐变颜色应用于单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46071140/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com