Changer la couleur des cellules en utilisant apache poi

J'utilise Apache POI pour lire des données dans un tableur de numéros de pièces. Je cherche le numéro de pièce dans notre base de données, si nous avons un dessin CAD DE LA PIÈCE Je couleur la cellule de numéro de pièce vert, si nous ne le faisons pas je la couleur rouge. Une fois le traitement terminé, la feuille de calcul est sauvegardée. Le problème, c'est que chaque cellule de cette colonne est verte. J'ai passé en revue le code, la logique pour chercher le numéro de pièce fonctionne bien et la logique pour déterminer quelle couleur la cellule devrait être et définir la couleur et le remplissage semble fonctionner aussi bien. Les idées de ce que je fais mal?

Merci.

//Check the parts
for(int r=1;r<sheet.getPhysicalNumberOfRows();r++) {
    String partNumber = null;
    switch(cell.getCellType()) {
        case HSSFCell.CELL_TYPE_NUMERIC:
            long pNum = (long) cell.getNumericCellValue();
            partNumber = String.valueOf(pNum);
            break;
        case HSSFCell.CELL_TYPE_STRING:
            partNumber = cell.getStringCellValue();
            break;
        default:
            logger.info("Part Number at row " + r + " on sheet " + partList.getSheetName(s) + "is of an unsupported type");
    }

    try {
        List<String> oldMaterialNumbers = getOldMaterialNumbers(partNumber);

        boolean gotDrawing = checkPartNumber(oldMaterialNumbers, partNumber);
        //If there's a drawing then color the row green, if not red.
        short bgColorIndex = gotDrawing
                                ?HSSFColor.LIGHT_GREEN.index //42
                                :HSSFColor.RED.index; //10

        HSSFCell curCell = row.getCell(partNumberColumn);
        HSSFCellStyle curStyle = curCell.getCellStyle();

        curStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        curStyle.setFillForegroundColor(bgColorIndex);

        curCell.setCellStyle(curStyle);

    }catch(Exception e) {
        throw e;
    }
}
21
demandé sur Striker 2012-07-17 23:31:09

5 réponses

version courte: créez des styles une seule fois, utilisez-les partout.

Version Longue: utilisez une méthode pour créer les styles dont vous avez besoin (attention à la limite sur le nombre de styles).

private static Map<String, CellStyle> styles;

private static Map<String, CellStyle> createStyles(Workbook wb){
        Map<String, CellStyle> styles = new HashMap<String, CellStyle>();
        DataFormat df = wb.createDataFormat();

        CellStyle style;
        Font headerFont = wb.createFont();
        headerFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
        headerFont.setFontHeightInPoints((short) 12);
        style = createBorderedStyle(wb);
        style.setAlignment(CellStyle.ALIGN_CENTER);
        style.setFont(headerFont);
        styles.put("style1", style);

        style = createBorderedStyle(wb);
        style.setAlignment(CellStyle.ALIGN_CENTER);
        style.setFillForegroundColor(IndexedColors.LIGHT_CORNFLOWER_BLUE.getIndex());
        style.setFillPattern(CellStyle.SOLID_FOREGROUND);
        style.setFont(headerFont);
        style.setDataFormat(df.getFormat("d-mmm"));
        styles.put("date_style", style);
        ...
        return styles;
    }

vous pouvez également utiliser des méthodes pour faire des tâches répétitives tout en créant des styles hashmap

private static CellStyle createBorderedStyle(Workbook wb) {
        CellStyle style = wb.createCellStyle();
        style.setBorderRight(CellStyle.BORDER_THIN);
        style.setRightBorderColor(IndexedColors.BLACK.getIndex());
        style.setBorderBottom(CellStyle.BORDER_THIN);
        style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
        style.setBorderLeft(CellStyle.BORDER_THIN);
        style.setLeftBorderColor(IndexedColors.BLACK.getIndex());
        style.setBorderTop(CellStyle.BORDER_THIN);
        style.setTopBorderColor(IndexedColors.BLACK.getIndex());
        return style;
    }

puis, dans votre code "principal", définissez le style à partir de la carte styles que vous avez.

Cell cell = xssfCurrentRow.createCell( intCellPosition );       
cell.setCellValue( blah );
cell.setCellStyle( (CellStyle) styles.get("style1") );
20
répondu Alfabravo 2012-07-17 20:13:05

Pour créer vos styles de cellule, voir: http://poi.apache.org/spreadsheet/quick-guide.html#CustomColors.

couleurs

HSSF:

HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet();
HSSFRow row = sheet.createRow((short) 0);
HSSFCell cell = row.createCell((short) 0);
cell.setCellValue("Default Palette");

//apply some colors from the standard palette,
// as in the previous examples.
//we'll use red text on a lime background

HSSFCellStyle style = wb.createCellStyle();
style.setFillForegroundColor(HSSFColor.LIME.index);
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);

HSSFFont font = wb.createFont();
font.setColor(HSSFColor.RED.index);
style.setFont(font);

cell.setCellStyle(style);

//save with the default palette
FileOutputStream out = new FileOutputStream("default_palette.xls");
wb.write(out);
out.close();

//now, let's replace RED and LIME in the palette
// with a more attractive combination
// (lovingly borrowed from freebsd.org)

cell.setCellValue("Modified Palette");

//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
);
//replacing lime with freebsd.org gold
palette.setColorAtIndex(HSSFColor.LIME.index, (byte) 255, (byte) 204, (byte) 102);

//save with the modified palette
// note that wherever we have previously used RED or LIME, the
// new colors magically appear
out = new FileOutputStream("modified_palette.xls");
wb.write(out);
out.close();

XSSF:

 XSSFWorkbook wb = new XSSFWorkbook();
    XSSFSheet sheet = wb.createSheet();
    XSSFRow row = sheet.createRow(0);
    XSSFCell cell = row.createCell( 0);
    cell.setCellValue("custom XSSF colors");

    XSSFCellStyle style1 = wb.createCellStyle();
    style1.setFillForegroundColor(new XSSFColor(new java.awt.Color(128, 0, 128)));
    style1.setFillPattern(CellStyle.SOLID_FOREGROUND);
5
répondu Elena 2013-01-16 11:24:20

je crois que c'est parce que cell.getCellStyle renvoie d'abord le style de cellule par défaut que vous changez ensuite.

créer des styles comme celui - ci et les appliquer aux cellules:

cellStyle = (XSSFCellStyle) cell.getSheet().getWorkbook().createCellStyle();

bien que comme l'affiche précédente a noté essayer de créer des styles et de les réutiliser.

il y a aussi une classe utilitaire dans la bibliothèque XSSF qui évitera le code que j'ai fourni et essaiera automatiquement de réutiliser les styles. Je ne me souviens pas de la main de classe 0ff.

3
répondu Alan Hay 2015-08-10 10:59:46

consultez l'exemple ici

http://svn.apache.org/repos/asf/poi/trunk/src/examples/src/org/apache/poi/ss/examples/BusinessPlan.java

style.setFillForegroundColor(IndexedColors.LIGHT_CORNFLOWER_BLUE.getIndex());
1
répondu user3308868 2014-04-02 07:51:33

pour apache POI 3.9 vous pouvez utiliser le code ci-dessous:

HSSFCellStyle style = workbook.createCellStyle()
style.setFillForegroundColor(HSSFColor.YELLOW.index)
style.setFillPattern((short) FillPatternType.SOLID_FOREGROUND.ordinal())

les méthodes pour la version 3.9 acceptent court et vous devriez faire attention aux entrées.

0
répondu Liviu Florin Ilie 2018-07-05 11:21:53