poi - 常用单元格样式

这是 4.1.2 版本的写法,poi 版本差异较大,按需调整。

import org.apache.poi.ss.usermodel.*;

/**
 * Excel 常用样式参考
 * <p>
 * 很复杂的样式,可以使用 Excel 模版,从现有的 Excel 中直接读取样式,
 * 平时很少写这些样式,留作参考。
 *
 * @author Mr.css
 * @version 2023-09-15 9:05
 */
public class Test {

    /**
     * 使用代码直接设置样式
     *
     * @param workbook -
     * @return -
     */
    private CellStyle getStyle(Workbook workbook) {
        CellStyle style = workbook.createCellStyle();

        // 设置底边框;
        style.setBorderBottom(BorderStyle.THIN);
        // 设置底边框颜色;
        style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
        // 设置左边框;
        style.setBorderLeft(BorderStyle.THIN);
        // 设置左边框颜色;
        style.setLeftBorderColor(IndexedColors.BLACK.getIndex());
        // 设置右边框;
        style.setBorderRight(BorderStyle.THIN);
        // 设置右边框颜色;
        style.setRightBorderColor(IndexedColors.BLACK.getIndex());
        // 设置顶边框;
        style.setBorderTop(BorderStyle.THIN);
        // 设置顶边框颜色;
        style.setTopBorderColor(IndexedColors.BLACK.getIndex());

        // 设置字体
        Font font = workbook.createFont();
        // 设置字体大小
        font.setFontHeightInPoints((short) 10);
        // 设置字体名字
        font.setFontName("微软雅黑");
        // 在样式用应用设置的字体;
        style.setFont(font);

        // 设置自动换行;
        style.setWrapText(false);
        // 设置水平对齐的样式为居中对齐;
        style.setAlignment(HorizontalAlignment.CENTER);
        // 设置垂直对齐的样式为居中对齐;
        style.setVerticalAlignment(VerticalAlignment.CENTER);

        // 设置填充样式(实心填充)
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        // 设置单元格颜色
        style.setFillForegroundColor(IndexedColors.LIME.getIndex());
        return style;
    }
}

posted on 2024-06-13 21:29  疯狂的妞妞  阅读(4)  评论(0编辑  收藏  举报

导航