如何获取指定单元格的(Java Apache POI HSSF)背景颜色?

11

我有一个现有的Excel电子表格,我正在访问并从中读取值,我正在使用Apache POI HSSF。

它是这样初始化的:

HSSFSheet sheet;
FileInputStream fis = new FileInputStream(this.file);
POIFSFileSystem fs = new POIFSFileSystem(fis);
HSSFWorkbook wb = new HSSFWorkbook(fs);
this.sheet = wb.getSheet(exsheet);

我正在遍历工作表中存在的所有单元格,这会产生一个单元格对象:

HSSFCell cell = (HSSFCell) cells.next();
请问熟悉该框架的人能否解释一下如何创建一个(HSSFColor)对象来表示工作表中每个单元格的背景颜色。
非常感谢。
编辑、更新
为了明确我的问题是:我应该如何创建/获取现有单元格背景颜色的 HSSFColor 对象?
cell.getCellStyle().getFillBackgroundColor(); 

这段代码仅返回一个短数字,而不是一个HSSFColor对象。感谢迄今为止提供的答案。


或者cell.getCellStyle().getFillForegroundColor(),我正在读取的Excel表格即使单元格已着色,背景颜色仍然返回相同的颜色。 - David Zhao
8个回答

7

5

获取颜色: getFillBackgroundColor返回的短值是Excel颜色索引。 您可以使用RMorrisey指示的最后一个代码,在HSSFColor哈希表中获取与索引对应的颜色。

设置颜色: 您需要创建一个自定义调色板,并更改给定索引处的颜色。然后,将该颜色应用于样式。

//creating a custom palette for the workbook
HSSFPalette palette = wb.getCustomPalette();
//replacing the standard red with freebsd.org red
palette.setColorAtIndex(HSSFColor.RED.index,
        (byte) 153,  //RGB red (0-255)
        (byte) 0,    //RGB green
        (byte) 0     //RGB blue
);
// or creating a new Color
HSSFColor myColor = palette.addColor((byte) 153, (byte) 0, (byte) 0); 
HSSFCellStyle style = wb.createCellStyle();

style.setFillForegroundColor(myColor);

敬礼

吉尔莫


2

XSSFCellStyle 的背景颜色信息可以通过以下方法获取:

XSSFCellStyle.getFillForegroundXSSFColor().getCTColor()

您可以将其打印出来,您就会看到它的结构。

1
要获取特定单元格的背景颜色(HEX格式),请使用以下代码:
cell.getCellStyle().getFillForegroundColorColor().getARGBHex()

注意到单词Color被使用了两次。

1

你可以这样做:

HSSFCell myCell = ...;
HSSFCellStyle myStyle = workbook.createCellStyle();
myStyle.setFillBackgroundColor(HSSFColor.BLUE);

myCell.setCellStyle(myStyle);

我相信对于一个给定的工作簿,样式数量是有限的;您应该尽可能地重用相同的样式对象。

[编辑:抱歉,那是要在单元格上设置颜色。要获取颜色,请使用以下方式:

myCell.getCellStyle().getFillBackgroundColor();

]

[编辑2:看了克雷格发布的自定义颜色信息,也许你可以尝试一下:

HSSFColor.getIndexHash().get(myCell.getCellStyle().getFillBackgroundColor())

]


非常感谢您迄今为止的回答,不幸的是它并不完全是一个解决方案,我现在已经重新澄清了问题。 - java
借助 Craig 的帖子,我更新了我的回答。 - RMorrisey

1
import java.io.File;    
import java.io.FileInputStream;       
import java.io.FileNotFoundException;   
import java.io.FileOutputStream;   
import java.io.IOException;   
import java.util.Iterator;    
import org.apache.poi.hssf.usermodel.HSSFPalette;    
import org.apache.poi.hssf.usermodel.HSSFSheet;    
import org.apache.poi.hssf.usermodel.HSSFWorkbook;    
import org.apache.poi.hssf.util.HSSFColor;    
import org.apache.poi.ss.usermodel.Cell;    
import org.apache.poi.ss.usermodel.CellStyle;    
import org.apache.poi.ss.usermodel.Row;    

/**
 * @author mohdasif_2688@rocketmail.com 
 *
 */

public class ExcelPractice {

    /**
     *  Must Read :     
     *  
     *  Code to get the background color from an excel sheet in RGB Format and display on the console    
     *  Save the content of the xls file into another OUTPUT.xls file.    
     *  Using a sample sheet with only first row filled with background color.    
     *  Code uses HSSF which means i am only using xls format.    
     *  Using poi-3.5-FINAL.jar    
     *  Solution with the output provided      
     *  Observation : Some Custom color's are not recognized as they may not be defined    
     *  in the excel color palette thus the code returns the almost similar color code.    
     */
    public static void main(String[] args) {
        try {
            FileInputStream fileInputStream=new FileInputStream(new     File("D:\\Excel_File.xls"));

            HSSFWorkbook workbook=new HSSFWorkbook(fileInputStream);
            HSSFSheet  sheet=workbook.getSheetAt(0);
            Iterator<Row> rowIterator= sheet.iterator();
            while (rowIterator.hasNext()) {
                Row row=rowIterator.next();

                Iterator<Cell> cellIterator=row.cellIterator();
                while (cellIterator.hasNext()) {
                    Cell cell = (Cell) cellIterator.next();

                        switch (cell.getCellType()) {
                        case Cell.CELL_TYPE_BOOLEAN:
                            System.out.println(cell.getBooleanCellValue()+"\t\t");  
                        System.out.println(cell.getCellStyle().getFillForegroundColor());
                        break;
                    case Cell.CELL_TYPE_NUMERIC:
                        System.out.println(cell.getNumericCellValue()+"\t\t");
                        System.out.println(cell.getCellStyle().getFillForegroundColor());
                        break;
                    case Cell.CELL_TYPE_STRING:
                        System.out.println(cell.getStringCellValue()+"\t\t");
                        //System.out.println(HSSFColor.getIndexHash().get(cell.getCellStyle().getFillBackgroundColor()));   
                        int num=cell.getColumnIndex();
                        Cell cell1 = row.getCell(num);
                        CellStyle cellStyle = cell1.getCellStyle();          
                        getColorPattern(cellStyle.getFillForegroundColor());
                        break;
                    default:
                        break;
                    }
                }
                System.out.println();

                fileInputStream.close();
                FileOutputStream fileOutputStream=new FileOutputStream(new File("D:\\OUTPUT.xls"));
                workbook.write(fileOutputStream);
                fileInputStream.close();
            }


    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.toString();
    }
    catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

//Method to identify the color pattern
private static short[] getColorPattern(short colorIdx){        
    short[] triplet = null;
    HSSFWorkbook workbook=new HSSFWorkbook();
    HSSFPalette palette = workbook.getCustomPalette();
    HSSFColor color = palette.getColor(colorIdx);
    triplet = color.getTriplet();       
    System.out.println("color : " + triplet[0] +"," + triplet[1] + "," +     triplet[2]);
    return triplet;
}
}

/** Output of the above code as executed in my system 
 S.NO.      
color : 255,255,0
VTU Number      
color : 0,128,0
First Name      
color : 51,204,204
Middle Name     
color : 255,0,0
Last Name       
color : 102,102,153
Branch      
color : 255,102,0
E-mail id       
color : 0,255,0
Mobile Number       
color : 255,255,255 
*/

Screen shot from the Excel_File.xls file


0
以下内容适用于XSSF,使用Scala编写,但确实展示了如何从对象模型中获取颜色。我想要从实际的RGB值实例化一个java.awt.Color对象(这部分很有用,因为我的调试器在断点处停止时会显示对象的真实颜色,而且这是导出到与Excel无关的系统的操作)。我忽略了颜色的Alpha值,我的Scala可能有点幼稚。如果这种方法对您不起作用,建议您设置断点并检查与getFillBackgroundColorColor()密切相关的方法调用的结果。
    val rgb: Array[Byte] = cell.getCellStyle.getFillForegroundColorColor.getRgb
    def toInt(b: Byte): Int = {
      if (b<0) 256+b else b
    }
    val rgbInts = rgb.map(toInt)
    val color = new Color(rgbInts(0),rgbInts(1),rgbInts(2))

0
对于读取xlsx文件的XSSF(也尝试了HSSF),经过一番努力,我终于发现getFillBackgroundXSSFColor()方法实际上返回的是Excel中“格式单元格”的“填充”选项卡中的“图案颜色”,而不是所谓的该选项卡中的“背景”颜色。我不确定这是否是预期的。
请参见下面的截图。返回的RGB实际上是FF0000,即红色。
        XSSFColor backgroundColor = cell.getCellStyle().
            getFillBackgroundXSSFColor();
    System.out.println("backgroundColor is "+backgroundColor.getARGBHex());

    Output: FFFF0000 //the first FF should be ignored.

目前,我还没有解决这个问题的方法,只能请求用户同时填写“图案颜色”。

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接