将边框添加到POI生成的Excel文件中的单元格
我正在使用POI来生成一个Excel文件。 我需要将边框添加到工作表中的特定单元格。
我怎样才能做到这一点?
在单元格中使用的样式设置边框将完成此操作。 例:
style.setBorderBottom(HSSFCellStyle.BORDER_MEDIUM); style.setBorderTop(HSSFCellStyle.BORDER_MEDIUM); style.setBorderRight(HSSFCellStyle.BORDER_MEDIUM); style.setBorderLeft(HSSFCellStyle.BORDER_MEDIUM);
HSSFCellStyle style=workbook.createCellStyle(); style.setBorderBottom(HSSFCellStyle.BORDER_THIN); style.setBorderTop(HSSFCellStyle.BORDER_THIN); style.setBorderRight(HSSFCellStyle.BORDER_THIN); style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
助手function:
private void setRegionBorderWithMedium(CellRangeAddress region, Sheet sheet) { Workbook wb = sheet.getWorkbook(); RegionUtil.setBorderBottom(CellStyle.BORDER_MEDIUM, region, sheet, wb); RegionUtil.setBorderLeft(CellStyle.BORDER_MEDIUM, region, sheet, wb); RegionUtil.setBorderRight(CellStyle.BORDER_MEDIUM, region, sheet, wb); RegionUtil.setBorderTop(CellStyle.BORDER_MEDIUM, region, sheet, wb); }
当你想在Excel中添加边框时,
String cellAddr="$A$11:$A$17";
setRegionBorderWithMedium(CellRangeAddress.valueOf(cellAddr1), sheet);
XSSF
边框
使用XSSFCellStyle
或XSSFBorderFormatting
(两个枚举引用相同的值)。
XSSFCellStyle cellStyle = workbook.createCellStyle(); cellStyle.setBorderBottom(XSSFCellStyle.BORDER_MEDIUM); cellStyle.setBorderTop(XSSFBorderFormatting.BORDER_MEDIUM);
边框颜色
使用setBorderColor(BorderSide, XSSFColor)
或setBottomBorderColor(XSSFColor)
(等同于上,左,右)。
XSSFCellStyle cellStyle = workbook.createCellStyle(); XSSFColor color = new XSSFColor(new java.awt.Color(128, 0, 128)); cellStyle.setBorderColor(XSSFCellBorder.BorderSide.BOTTOM, color); cellStyle.setBottomBorderColor(color);
在较新的apache poi版本中:
XSSFCellStyle style = workbook.createCellStyle(); style.setBorderTop(BorderStyle.MEDIUM); style.setBorderBottom(BorderStyle.MEDIUM); style.setBorderLeft(BorderStyle.MEDIUM); style.setBorderRight(BorderStyle.MEDIUM);
要在Apache POI中创build边框,您应该…
1:创build一个样式
final XSSFCellStyle style = workbook.createCellStyle();
2:然后你必须创build边框
style.setBorderBottom( new XSSFColor(new Color(235,235,235));
3:然后你必须设置边框的颜色
style.setBottomBorderColor( new XSSFColor(new Color(235,235,235));
4:然后将样式应用于单元格
cell.setCellStyle(style);