首页 文章

Apache POI,创建新单元格会覆盖行样式

提问于
浏览
12

我正在使用Apache POI将数据导出到.xlsx文件,我想要设置文件中包含的一些行和单元格 .

我正在使用XSSF,因为该文件将在Excel 2007中读取 .

基本上,我的问题是我正在尝试设置一个行样式,如下例所示,它为索引0处的整行设置黑色前景色 . 它工作正常,但每当我创建一个新单元格时,新创建的cell没有样式,好像它覆盖了我指定的行样式 .

这是一个代码片段,用于演示我正在做的事情:

XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet("mySheet");
XSSFRow row = sheet.createRow(0);

XSSFCellStyle myStyle = wb.createCellStyle();           

myStyle.setFillForegroundColor(new XSSFColor(new Color(255, 255, 255)));
myStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);

row.setRowStyle(myStyle); //This works, the whole row is now black

row.createCell(0); // This cell doesn't have a style, the rest of the line stays stylized
row.getCell(0).setCellValue("Test");

我也试过* row.createCell(0,Cell.CELL_TYPE_STRING); *,但它没有改变任何东西 .

完成我想做的事的正确方法是什么?我想这样做,所以我不必在创建它之后设置每个单元格的样式,因为同一行上的所有单元格都具有相同的样式 .

3 回答

  • 9

    将样式设置为新创建的单元格,例如下面:

    XSSFCell newCell = row.createCell(0);
        newCell.setCellStyle(myStyle);
    
  • 10

    即使您使用样式创建一行,也不会影响其创建的单元格 . 创建单元格具有自己的单元格样式 . row style 不会自动覆盖 cell style . 如果要在单元格中使用行样式,则必须再次设置 .

    即使您在结尾处设置了 row style ,它也不会对单元格产生影响 .

    CreationHelper createHelper = wb.getCreationHelper();
    Sheet sheet = wb.createSheet("new sheet");
    Row r = sheet.createRow(0);
    r.setRowStyle(rowStyle);
    
    Cell c1 = r.createCell(0);
    c1.setCellValue("Test 1");
    c1.setCellStyle(rowStyle);
    
  • 0

    我同意“setRowStyle”不能正常工作 .

    我创建了自己的函数,用于将样式应用于范围(可以是行或多行)

    public void applyStyleToRange(Sheet sheet, CellStyle style, int rowStart, int colStart, int rowEnd, int colEnd) {
        for (int r = rowStart; r <= rowEnd; r++) {
            for (int c = colStart; c <= colEnd; c++) {
                Row row = sheet.getRow(r);
    
                if (row != null) {
                    Cell cell = row.getCell(c);
    
                    if (cell != null) {
                        cell.setCellStyle(style);
                    }
                }
            }
        }
    }
    

相关问题