在Java中以十六进制形式获取.xls工作表中单元格的文本和背景色

时间:2018-07-26 06:33:37

标签: java excel apache-poi xls poi-hssf

我需要验证单元格Discount的文本的十六进制颜色是#FF1493,同一单元格的背景的十六进制颜色是#FFC0CB。

我正在获取背景的rgb颜色,但无法将其转换为十六进制,并且无法获取文本的十六进制颜色。

请在下面的代码和表格的屏幕快照中找到,以使您对有问题的单元格有一个了解。

        String fileFormat = FileManagement.getFileFormat(new java.io.File(fileName));
    List<String> content = new ArrayList<>();
    HSSFWorkbook workbookXLS = null;
    try {
        InputStream ExcelFileToRead = new FileInputStream(fileName);
        //Getting the workbook instance for .XLS('old' excel format) file
        workbookXLS = new HSSFWorkbook(ExcelFileToRead);
    } catch (FileNotFoundException | NotOLE2FileException ex) {
        fail(ex.getMessage() + "! File: " + fileName);
    }
    //getting the first or specific sheet from the workbook
    HSSFSheet sheetXLS = workbookXLS.getSheetAt(0);
    HSSFRow rowXLS;
    HSSFCell cellXLS;
    //Iterating all the rows in the sheet
    Iterator rows = sheetXLS.rowIterator();
    while (rows.hasNext()) {
        rowXLS = (HSSFRow) rows.next();
        if (rowXLS.getRowNum() = 7) {
            cellXLS = rowXLS.getCell(0);
            if (cellXLS.getCellTypeEnum() == CellType.STRING) {
                if (cellXLS.getStringCellValue().equals("loads : Id")) {
                    Color colorFG = cellXLS.getCellStyle().getFillForegroundColorColor();
                    short[] rgb = HSSFColor.toHSSFColor(colorFG).getTriplet();   //this returns the rgb color of the background -> 255 192 203
                    System.out.println("THE FIRST COLOR RGB IS " + rgb[0] + "SECOND " + rgb[1] + "THIRD " + rgb[2]);
                    Color colorBG = cellXLS.getCellStyle().getFillBackgroundColorColor();
                    short[] hshs = HSSFColor.toHSSFColor(colorBG).getTriplet();  //this returns ->  0 0 0
                    System.out.println("THE SECOND COLOR RGB IS" + hshs[0] + "SECOND " + hshs[1] + "THIRD " + hshs[2]);
                }
            } else if (cellXLS.getCellTypeEnum() == CellType.NUMERIC) {
                content.add(String.valueOf(cellXLS.getNumericCellValue()));
            }
        }
    }[![enter image description here][1]][1]

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:3)

您可以尝试以下操作:

String hex = String.format("#%02x%02x%02x", rgb[0], rgb[1], rgb[2]); 

或大写X:

String hex = String.format("#%02X%02X%02X", rgb[0], rgb[1], rgb[2]);