Apache Poi将梯度颜色应用于单元格
问题描述:
我一直在搜索网页,并没有发现使用Apache Poi将渐变颜色应用于Excel单元格的真正好例子。Apache Poi将梯度颜色应用于单元格
我发现的例子很旧,在当前的Apache Poi版本中,类已经不存在了。我目前正在使用Apache Poi版本3.16。
有人可以指出使用poi库将渐变颜色应用于excel表格所需的步骤。所有提示都表示赞赏。
答
使用默认实际的apache poi
版本始终不可能设置渐变单元格填充。
所以我怀疑你找到的代码是为XSSF
(*.xlsx
)和代码,你发现它只是没有提到这个代码需要的所有类路径的模式ooxml-schemas-1.3.jar
的全部罐子在faq-N10025提到。
以下示例可以正常工作,但也需要类路径中所有模式ooxml-schemas-1.3.jar
的完整jar,如faq-N10025中所述。
它首先将图案填充设置设置为CellStyle
,只有一些填充以从中获取填充索引。然后它得到CellStyle
中使用的低级CTFill
。然后它取消图案填充,然后设置渐变填充。我想使用grepcode.com。
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);
workbook.write(new FileOutputStream("CreateExcelCellGradientFillColor.xlsx"));
workbook.close();
}
}
谢谢,真的澄清我的问题,我已经包括了我的项目中的第二个wvend Maven依赖项,因为有些类无法解析。 我用poi-ooxml-schemas作为依赖,这是错误的。现在更改为ooxml-schemas,并且可以找到所有类。感谢您的澄清。 –