POI操作Excel--设置单元格对齐方式--day03

设置单元格的对齐方式

1.注意:

1.如果每个单元格(cell)的样式都不一样,必须每个单元格都创建一个CellStyle,否则不生效;

2.day03关闭流的方式, 采用了JDK 7的try(),,写在try括号里的资源会自动关闭。

    /**
     * 设置对齐方式
     */
    @Test
    public void setAlignment() {
        // 创建Excel工作簿
        Workbook workbook = new XSSFWorkbook();

        // 创建sheet
        Sheet sheet = workbook.createSheet(WorkbookUtil.createSafeSheetName("第一页?"));

        // 创建行和单元格并设置对齐方式
        generateRowAndCell(sheet, workbook, 0, 0, HorizontalAlignment.CENTER, VerticalAlignment.CENTER);
        generateRowAndCell(sheet, workbook, 1, 0, HorizontalAlignment.LEFT, VerticalAlignment.BOTTOM);
        generateRowAndCell(sheet, workbook, 2, 0, HorizontalAlignment.RIGHT, VerticalAlignment.TOP);
        generateRowAndCell(sheet, workbook, 3, 0, HorizontalAlignment.CENTER_SELECTION, VerticalAlignment.DISTRIBUTED);
        generateRowAndCell(sheet, workbook, 4, 0, HorizontalAlignment.DISTRIBUTED, VerticalAlignment.JUSTIFY);
        generateRowAndCell(sheet, workbook, 5, 0, HorizontalAlignment.FILL, VerticalAlignment.CENTER);
        generateRowAndCell(sheet, workbook, 6, 0, HorizontalAlignment.GENERAL, VerticalAlignment.CENTER);
        generateRowAndCell(sheet, workbook, 7, 0, HorizontalAlignment.JUSTIFY, VerticalAlignment.CENTER);

        // 创建文件, 写出, 关闭workBook
        try(OutputStream outputStream = new FileOutputStream("demo11.xlsx")) {
            workbook.write(outputStream);
            workbook.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @Description: 创建Excel的行和单元格, 并设置对齐方式
     * @param:  sheet
     * @param:  cellStyle
     * @Return: void
     * @Author: SLY
     * @Date:   2019/2/28 23:11
     */
    private void generateRowAndCell(Sheet sheet, Workbook workbook, int rowIndex, int cellIndex,
                                    HorizontalAlignment horizontalAlignment, VerticalAlignment verticalAlignment) {
        // 创建row
        Row row = sheet.createRow(rowIndex);
        row.setHeightInPoints(30);
        // 创建cell, 设置样式
        Cell cell = row.createCell(cellIndex);
        CellStyle cellStyle = workbook.createCellStyle();
        // 水平对齐
        cellStyle.setAlignment(horizontalAlignment);
        // 垂直对齐
        cellStyle.setVerticalAlignment(verticalAlignment);
        cell.setCellValue("对齐");
        cell.setCellStyle(cellStyle);
    }

2.效果图(第六行的两个“对齐”,实际只有一个,只是看起来有两个)

POI操作Excel--设置单元格对齐方式--day03_第1张图片

你可能感兴趣的:(POI操作Excel系列)