首页 文章

设置单元格样式不起作用

提问于
浏览
7

我正在使用apache poi和XLSX文件 . 我使用xssf类动态创建电子表格 . 我想在for循环中设置单元格的样式,但它似乎不起作用......这是我的代码:

for(int i=1;i<=gc.getActualMaximum(GregorianCalendar.DAY_OF_MONTH);i++,gc.add(GregorianCalendar.DATE, 1),righe++){
        Row r = foglio.createRow(righe);

        if(getDayOfWeek(gc)== 6 || getDayOfWeek(gc) == 7){
            XSSFCellStyle cs1 = wb.createCellStyle();
            cs1.setFillBackgroundColor(IndexedColors.YELLOW.getIndex());
            cs1.setFillPattern(CellStyle.SOLID_FOREGROUND);
            XSSFFont f = wb.createFont();
            f.setBold(true);
            f.setColor(IndexedColors.RED.getIndex());
            cs1.setFont(f);
            Cell c1 = r.createCell(0);
                 c1.setCellValue(cost.getGiorni().get(getDayOfWeek(gc)-1).getNomeGiorno());
                 c1.setCellStyle(cs1);
            Cell c2 = r.createCell(1);
                 c2.setCellValue(i);
                 c2.setCellStyle(cs1);
        }               
        r.createCell(0).setCellValue(cost.getGiorni().get(getDayOfWeek(gc)-1).getNomeGiorno());
        r.createCell(1).setCellValue(i);

...这只是代码的一部分......我无法理解为什么不工作 . 似乎像cellstyle被忽略或者被淹没....

任何线索?

2 回答

  • 7

    您可以使用以下方法,这可能会解决您的问题 .

    public static void setCellColorAndFontColor(XSSFCell cell, IndexedColors FGcolor, IndexedColors FontColor ){
        XSSFWorkbook wb = cell.getRow().getSheet().getWorkbook();
        CellStyle style = wb.createCellStyle();
        XSSFFont font = wb.createFont();
        font.setBold(true);
        font.setColor(FontColor.getIndex());
        style.setFont(font);
        style.setFillForegroundColor(FGcolor.getIndex());
        style.setFillPattern(CellStyle.SOLID_FOREGROUND);
        cell.setCellStyle(style);
    }
    

    当你调用这种方法时,应该是这样的

    setCellColorAndFontColor(cell, IndexedColors.BLACK, IndexedColors.WHITE);
    

    将在工作表中创建带有黑色单元格背景颜色的粗体和白色字体文本颜色 .

  • 4

    CellStyles是每个工作簿,并且Excel对允许文件允许的数字施加了硬限制,因此您需要确保在循环外部创建单元格样式 .

    您的代码看起来像:

    XSSFCellStyle cs1 = wb.createCellStyle();
    cs1.setFillBackgroundColor(IndexedColors.YELLOW.getIndex());
    cs1.setFillPattern(CellStyle.SOLID_FOREGROUND);
    
    XSSFFont f = wb.createFont();
    f.setBold(true);
    f.setColor(IndexedColors.RED.getIndex());
    cs1.setFont(f);
    
    for(int i=1;i<=gc.getActualMaximum(GregorianCalendar.DAY_OF_MONTH) i++,gc.add(GregorianCalendar.DATE, 1),righe++){
        Row r = foglio.createRow(righe);
    
        if(getDayOfWeek(gc)== 6 || getDayOfWeek(gc) == 7){
            Cell c1 = r.createCell(0);
            c1.setCellValue(cost.getGiorni().get(getDayOfWeek(gc)-1).getNomeGiorno());
            c1.setCellStyle(cs1);
            Cell c2 = r.createCell(1);
            c2.setCellValue(i);
            c2.setCellStyle(cs1);
        }
    }
    

    如果您的样式问题看起来不像您期望的那样,最好的选择是在Excel中为您想要的样式设置样式,保存文件,将其读入POI,并查看Excel编写的单元格样式 . 有时,Excel可以做一些需要习惯的奇怪的事情,所以检查它做了什么来计算出你需要做的事情!

相关问题