当前位置: 首页 > 知识库问答 >
问题:

使用ApachePOI更改单元格颜色

昌学
2023-03-14

我正在使用Apache POI读取零件编号电子表格中的数据。我在我们的数据库中查找零件编号,如果我们有零件的计算机辅助设计图纸,我将零件编号单元格涂成绿色,如果没有,我将其涂成红色。处理完成后,将保存电子表格。我遇到的问题是那列中的每个细胞都是绿色的。我已经完成了代码,查找零件号的逻辑工作正常,确定单元格应该是什么颜色以及设置颜色和填充的逻辑似乎也工作正常。知道我做错了什么吗?

谢谢

//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;
    }
}

共有3个答案

乌和畅
2023-03-14

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

创建这样的样式并将其应用到单元格:

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

尽管如前一张海报所述,尝试创建样式并重用它们。

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

华欣怡
2023-03-14

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

自定义颜色

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);
吉玉石
2023-03-14

简短版本:只创建一次样式,在任何地方使用它们。

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

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时,还可以使用方法执行重复任务

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;
    }

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

Cell cell = xssfCurrentRow.createCell( intCellPosition );       
cell.setCellValue( blah );
cell.setCellStyle( (CellStyle) styles.get("style1") );
 类似资料:
  • 问题内容: 我在GUI应用程序中使用JTable作为网格来表示游戏的位置。我希望代表对象某个位置的表的单元格具有某种颜色,并且在某些操作上希望移动的对象(即在Grid / JTable中四处移动的颜色单元格)。我知道我可以通过创建一个可扩展的类来更改单元格的颜色,这是唯一的方法吗?还是有一种更简单的方法来改变单元格颜色?对于这样的应用程序,JXTable是否比JTable好? 编辑: 我没有包括以

  • 问题内容: 我想制作一个可编辑的表,然后检查数据以确保其有效。我不确定如何仅更改一个单元格的颜色。我想要一个单元格,例如(0,0)并将前景颜色设置为红色。我已经阅读了SO和Oracle上有关自定义ColorRenderer的其他文章,但是我不知道如何使用它。 谢谢。 问题答案: 假设您要用其他颜色渲染的单元格代表一种状态(我将以“拒绝并批准”为例)。然后,我将在我的表模型中实现一个名为getSta

  • 问题内容: 我试图使自己熟悉JTables,TableModels,JTableHeaders,渲染器等。我试图制作一个简单的虚拟表(出于练习目的),看起来像这样: 我还希望B2单元格-并且只有该单元格-具有蓝色(Color.BLUE)背景-所有其他单元格都可以具有自动分配的Swing默认颜色。 我的代码在下面,并且基于我在本网站和整个互联网上发现的无数示例。但是我没有得到想要的结果。相反,我得到

  • 我已经了解到您不能将事件添加到默认的calendarview(它只是在用户的默认日历中处理),所以我使用了caldroid https://github.com/roomorama/caldroid/blob/master/readme.md,到目前为止,它对文档很有帮助,但当涉及到一件事时,我感到迷茫。 我想做的是改变任何日期的颜色,有一个事件。文档中说要制作一个drawable并将其放入单元格

  • 我需要用Java和Jsoup解析一个表,并根据它的值改变单元格的颜色。这就是html表格的外观,也是单元格颜色需要定义的方式 我写了一个脚本,可以准备好单元格的值并从中更改文本,但是我无法也更改颜色。 这是我收到的错误: