2017-09-06 58 views
0

我一直在搜索網頁,並沒有發現使用Apache Poi將漸變顏色應用於Excel單元格的真正好例子。Apache Poi將梯度顏色應用於單元格

我發現的例子很舊,在當前的Apache Poi版本中,類已經不存在了。我目前正在使用Apache Poi版本3.16。

有人可以指出使用poi庫將漸變顏色應用於excel表格所需的步驟。所有提示都表示讚賞。

回答

1

使用默認實際的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(); 
} 
} 
+0

謝謝,真的澄清我的問題,我已經包括了我的項目中的第二個wvend Maven依賴項,因爲有些類無法解析。 我用poi-ooxml-schemas作爲依賴,這是錯誤的。現在更改爲ooxml-schemas,並且可以找到所有類。感謝您的澄清。 –