【问题标题】:Multiple cell align in same row (Apache POI)多个单元格在同一行中对齐(Apache POI)
【发布时间】:2016-12-25 09:40:29
【问题描述】:

我正在使用 Apache POI 3.7,我正在尝试创建一个行,其中一些单元格左对齐而其他单元格居中对齐。

我试过了:

if(isNumeric()){ cellStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER); }else{ cellStyle.setAlignment(XSSFCellStyle.ALIGN_LEFT); }

我也试过了:

cellStyle.setAlignment((short)0) , cellStyle.setAlignment((short)1) ...

无论如何,当我生成 Excel 文档时,该行中的所有单元格都是左对齐或居中对齐,但没有混合。

我什至不知道是否有可能做我正在尝试的事情。

谢谢

【问题讨论】:

    标签: java excel apache-poi


    【解决方案1】:

    根据 Cell .setCellStyle(CellStyle style) 方法的 javadoc,样式应该是通过调用 Workbook 上的 createCellStyle() 方法创建的 CellStyle。试试以下方法:

    CellStyle centeredStyle = workbook.createCellStyle();
    centeredStyle.setAlignment(CellStyle.ALIGN_CENTER);
    
    CellStyle leftStyle = workbook.createCellStyle();
    leftStyle.setAlignment(CellStyle.ALIGN_LEFT);
    
    Sheet sheet = workbook.getSheetAt(0);
    for(Row row : sheet.rowIterator()) {
        for(Cell cell : row.cellIterator()) {
            CellStyle cellStyle = (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) ? centeredStyle : leftStyle;
            cell.setCellStyle(cellStyle);
        }
    }
    

    【讨论】:

      【解决方案2】:

      所以看起来你有一个单元格样式,并在左对齐和居中对齐之间不断变化。单元格共享样式,因此如果您更改一个单元格的样式,则该样式已分配给的所有单元格的样式都会更改。要获得多个对齐,您需要多个样式

      Workbook wb = new XSSFWorkbook();
      Sheet sh = wb.createSheet("Sheet1");
      CellStyle left = wb.createCellStyle();
      left.setAlignment(CellStyle.ALIGN_LEFT);
      CellStyle center = wb.createCellStyle();
      center.setAlignment(CellStyle.ALIGN_CENTER);
      
      Row r1 = sh.createRow(1);
      Cell c1 = r1.createCell(1);
      c1.setCellStyle(left);
      c1.setCellValue("Left justified text");
      Cell c2 = r1.createCell(2);
      c2.setCellStyle(center);
      c2.setCellValue(1234);
      Cell c3 = r1.createCell(3);
      c3.setCellStyle(left);
      c3.setCellValue("More Left Justified Text");
      
      FileOutputStream fileOut = new FileOutputStream("CellAlignTest.xlsx");
      wb.write(fileOut);
      wb.close();
      fileOut.close();
      

      这里还有一点需要注意的是,您可以使用的样式数量有限,因此如果您要创建大型工作表,则必须共享它们。

      【讨论】:

      • 不知道单元格共享样式,您的代码就像我预期的那样工作!我还阅读了您的最后一条笔记,工作簿的样式限制为 4.000。谢谢
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多