POI单元格格式设置

POI单元格格式设置

初始化操作

1
2
3
4
5
6
7
8
//获取工作簿对象
Workbook workbook = new XSSFWorkbook();
//获取表格对象
Sheet sheet = workbook.createSheet("sheet")
//获取单元格样式对象
CellStyle cellStyle = worbook.createCellStyle();
//获取单元格字体对象
Font font = worbook.createFont();

设置居中对齐

1
2
3
4
5
6
7
8
9
10
//设置水平对齐的样式为居中对齐;  
cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
//设置垂直对齐的样式为居中对齐;
cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

//POI 3.17的写法
//设置水平对齐的样式为居中对齐;
cellStyle.setAlignment(HorizontalAlignment.CENTER);
//设置垂直对齐的样式为居中对齐;
cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);

设置背景色

1
2
cellStyle.setFillForegroundColor(IndexedColors.PALE_BLUE.getIndex());
cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);

设置边框

1
2
3
4
5
6
7
8
//设置上边框
cellStyle.setBorderTop(BorderStyle.THIN);
//设置下边框
cellStyle.setBorderBottom(BorderStyle.THIN);
//设置左边框
cellStyle.setBorderLeft(BorderStyle.THIN);
//设置右边框
cellStyle.setBorderRight(BorderStyle.THIN);

设置字体

1
2
font.setFontName("宋体");
cellStyle.setFont(font);

字体加粗

1
2
font.setBold(true);
cellStyle.setFont(font);

合并单元格

1
2
3
4
5
6
7
8
9
10
11
12
//CellRangeAddress构造方法四个参数为:初始行、截止行、初始列、截止列
CellRangeAddress region = new CellRangeAddress(0,0,0,0);
sheet.addMergedRegion(region);
//合并单元格后边框不会自动合并,需要额外操作
setRegionBorder(BorderStyle.THIN,region,sheet);

public static void setRegionBorder(BorderStyle border,CellRangeAddress region,Sheet sheet) {
RegionUtil.setBorderTop(border,region,sheet);
RegionUtil.setBorderBottom(border,region,sheet);
RegionUtil.setBorderLeft(border,region,sheet);
RegionUtil.setBorderRight(border,region,sheet);
}
如果对您有帮助,可以打赏呦!