POI单元格样式、行高列宽、合并单元格设置

单元格样式

文字对齐方式

设置文字在水平、垂直方向居中显示

// 设置单元格内容水平、垂直居中
style.setAlignment(HorizontalAlignment.CENTER);
style.setVerticalAlignment(VerticalAlignment.CENTER);

单元格填充背景色

设置单元格填充背景颜色和填充方式

// 设置单元格填充的 颜色和图案。这两个同时设置才生效
style.setFillForegroundColor(IndexedColors.GREY_50_PERCENT.getIndex());
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);

单元格边框样式

主要设置边框的颜色及线条样式

// 设置单元格边框的颜色
style.setBorderRight(BorderStyle.THIN);
style.setRightBorderColor(IndexedColors.BLUE1.getIndex());
style.setBorderLeft(BorderStyle.THIN);
style.setLeftBorderColor(IndexedColors.RED.getIndex());
style.setBorderTop(BorderStyle.THIN);
style.setTopBorderColor(IndexedColors.YELLOW.getIndex());
style.setBorderBottom(BorderStyle.THIN);
style.setBottomBorderColor(IndexedColors.PINK.getIndex());

字体设置

设置单元格字体

// 设置单元格字体
Font headerFont = wb.createFont();
headerFont.setFontName("Arial");   // 设置字体
headerFont.setFontHeightInPoints((short) 14);  // 设置字体大小
headerFont.setBold(true); // 字体加粗
headerFont.setItalic(false);// 斜体
headerFont.setColor(IndexedColors.WHITE.getIndex()); // 字体颜色

style.setFont(headerFont); // 将字体关联到样式中

行高与列宽

Excel 中的行高与列宽,由于计算单位的不同。我们在写代码的时候需要先进行转换,在设置行高与列宽

例如:

Excel 中的行高30, 列宽20

则在程序中行高:(short)(20*30),列宽:(int) ((20 + 0.72) * 256)

row1.setHeight((short)(20*30));
// 设置第3列的列宽为20
int width = (int) ((20 + 0.72) * 256);
sheet.setColumnWidth(2,width);

单元格合并

// 单元格合并
Row row = sheet.createRow(0);
Cell cell1 = row.createCell(0);
sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 4));


版权声明:本文为u010559460原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。