获取 .xls sheet 中单元格的文本和背景颜色作为 java 中的十六进制

Get text and background color of a cell in .xls sheet as hex in java

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

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

请在下面找到 table 的代码和屏幕截图,以便您了解有问题的单元格。

        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]

我们将不胜感激任何帮助。

你可以试试这个:

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]);