首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用apache poi更改单元格颜色

使用apache poi更改单元格颜色
EN

Stack Overflow用户
提问于 2012-07-18 03:31:09
回答 5查看 116K关注 0票数 25

我正在使用Apache POI读取部件号电子表格中的数据。我在我们的数据库中查找零件编号,如果我们有零件的CAD图纸,我将零件编号单元格着色为绿色,如果没有,我将其着色为红色。处理完成后,保存电子表格。我遇到的问题是,该列中的每个单元格都显示为绿色。我已经单步执行了代码,查找零件号的逻辑工作正常,确定单元格应该是什么颜色以及设置颜色和填充的逻辑似乎也工作得很好。你知道我哪里做错了吗?

谢谢。

代码语言:javascript
复制
//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;
    }
}
EN

回答 5

Stack Overflow用户

发布于 2012-07-18 04:13:05

简而言之:只创建一次样式,到处使用它们。

长版本:使用一种方法来创建所需的样式(注意样式数量的限制)。

代码语言:javascript
复制
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;
    }

在创建样式hashmap时,还可以使用方法执行重复性任务。

代码语言:javascript
复制
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;
    }

然后,在你的“主”代码中,从你拥有的样式图中设置样式。

代码语言:javascript
复制
Cell cell = xssfCurrentRow.createCell( intCellPosition );       
cell.setCellValue( blah );
cell.setCellStyle( (CellStyle) styles.get("style1") );
票数 23
EN

Stack Overflow用户

发布于 2013-01-16 19:24:21

要创建单元格样式,请参阅:http://poi.apache.org/spreadsheet/quick-guide.html#CustomColors

自定义颜色

HSSF:

代码语言:javascript
复制
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:

代码语言:javascript
复制
 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);
票数 4
EN

Stack Overflow用户

发布于 2012-07-18 06:07:05

我相信这是因为cell.getCellStyle最初会返回默认的单元格样式,然后您会对其进行更改。

创建如下样式并将其应用于单元格:

代码语言:javascript
复制
cellStyle = (XSSFCellStyle) cell.getSheet().getWorkbook().createCellStyle();

尽管如上一篇帖子所说,尝试创建样式并重用它们。

XSSF库中还有一些实用程序类,可以避免我提供的代码,并自动尝试和重用样式。记不住手的班级了。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11529542

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档