我需要使用Apache POI创建一个如下图所示的渐变填充单元格。
我使用此代码创建一个简单的渐变填充,但我需要完全像图片。
谢谢大家的帮助。
PS:图片显示,我的意思是渐变填充单元格。
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) 102; // green
rgb1[2] = (byte) 102; // 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(45.0);
ctgradientfill.addNewStop().setPosition(0.0);
ctgradientfill.getStopArray(0).addNewColor().setRgb(rgb1);
ctgradientfill.addNewStop().setPosition(0.9);
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("C:/file.xlsx"));
workbook.close();
感谢您的帮助。
答案 0 :(得分:0)
这是通过Macro Recorder生成渐变填充的代码:
Sub Makro3()
'
' Makro3 Makro
'
'
Range("A1").Select
With Selection.Interior
.Pattern = xlPatternLinearGradient
.Gradient.Degree = 45
.Gradient.ColorStops.Clear
End With
With Selection.Interior.Gradient.ColorStops.Add(0)
.ThemeColor = xlThemeColorDark1
.TintAndShade = 0
End With
With Selection.Interior.Gradient.ColorStops.Add(1)
.ThemeColor = xlThemeColorAccent1
.TintAndShade = 0
End With
ActiveWindow.SmallScroll Down:=4
End Sub
只需按下记录宏的红点,然后自己制作渐变填充。 MS Excel将为您生成代码。
答案 1 :(得分:0)
尝试通过录制宏获得您想要的内容,然后播放并查看其工作原理 但如果失败,您可以使用此参考VBA Code Cell Fills (Color, Patterns, & Gradients)
手动编辑答案 2 :(得分:-1)
Sub gradient()
'
' gradient Macro
'
'
With Selection.Interior
.Pattern = xlPatternRectangularGradient
.gradient.RectangleLeft = 1
.gradient.RectangleRight = 1
.gradient.RectangleTop = 0
.gradient.RectangleBottom = 0
.gradient.ColorStops.Clear
End With
With Selection.Interior.gradient.ColorStops.Add(0)
.ThemeColor = xlThemeColorDark1
.TintAndShade = 0
End With
With Selection.Interior.gradient.ColorStops.Add(1)
.ThemeColor = xlThemeColorAccent5
.TintAndShade = -0.498031556138798
End With
End Sub