单元格样式
文字对齐方式
设置文字在水平、垂直方向居中显示
// 设置单元格内容水平、垂直居中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列的列宽为20int 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));