JAVA Apache POI Excel:为单元格区域添加边框
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JAVA Apache POI Excel:为单元格区域添加边框相关的知识,希望对你有一定的参考价值。
有没有办法在Java POI中使用Java为cellrange添加边框?
像A1:B2应该得到一个左上角 - 右下角的厚边框式?
我知道如何创建和应用单个单元格的样式,我可能会迭代通过单元格并应用适当的样式,但我相信有一个更简单的方法。
答案
我已经弄清楚了。在apache poi页面上实际上有一个示例,我只是找不到我一直在搜索的关键字。
CellRangeAddress region = CellRangeAddress.valueOf(A1:B2);
short borderStyle = CellStyle.BORDER_MEDIUM;
RegionUtil.setBorderBottom(borderStyle, region, activeSheet, excelWorkbook);
RegionUtil.setBorderTop(borderStyle, region, activeSheet, excelWorkbook);
RegionUtil.setBorderLeft(borderStyle, region, activeSheet, excelWorkbook);
RegionUtil.setBorderRight(borderStyle, region, activeSheet, excelWorkbook);
另一答案
事情在3.16发生了变化
CellRangeAddress region = new CellRangeAddress(6, 8, 1, 10);
RegionUtil.setBorderBottom(BorderStyle.THIN, region, sheet);
RegionUtil.setBorderTop(BorderStyle.THIN, region, sheet);
RegionUtil.setBorderLeft(BorderStyle.THIN, region, sheet);
RegionUtil.setBorderRight(BorderStyle.THIN, region, sheet);
另一答案
在我的情况下,RegionUtil将除了白色以外的所有背景颜色都变为黑色。这是我的解决方法:
public final class BorderUtils {
public static void setBorder(Sheet sheet, BorderStyle borderStyle, CellRangeAddress region) {
setBorderTop(sheet, borderStyle, region);
setBorderBottom(sheet, borderStyle, region);
setBorderLeft(sheet, borderStyle, region);
setBorderRight(sheet, borderStyle, region);
}
public static void setBorderTop(Sheet sheet, BorderStyle borderStyle, CellRangeAddress region) {
Row row = sheet.getRow(region.getFirstRow());
for (int i=region.getFirstColumn() ; i<=region.getLastColumn() ; i++) {
Cell cell = row.getCell(i);
CellStyle cellStyle = cloneCellStyle(sheet, cell);
cellStyle.setBorderTop(borderStyle);
cell.setCellStyle(cellStyle);
}
}
public static void setBorderBottom(Sheet sheet, BorderStyle borderStyle, CellRangeAddress region) {
Row row = sheet.getRow(region.getLastRow());
for (int i=region.getFirstColumn() ; i<=region.getLastColumn() ; i++) {
Cell cell = row.getCell(i);
CellStyle cellStyle = cloneCellStyle(sheet, cell);
cellStyle.setBorderBottom(borderStyle);
cell.setCellStyle(cellStyle);
}
}
public static void setBorderLeft(Sheet sheet, BorderStyle borderStyle, CellRangeAddress region) {
for (int i=region.getFirstRow() ; i<=region.getLastRow() ; i++) {
Cell cell = sheet.getRow(i).getCell(region.getFirstColumn());
CellStyle cellStyle = cloneCellStyle(sheet, cell);
cellStyle.setBorderLeft(borderStyle);
cell.setCellStyle(cellStyle);
}
}
public static void setBorderRight(Sheet sheet, BorderStyle borderStyle, CellRangeAddress region) {
for (int i=region.getFirstRow() ; i<=region.getLastRow() ; i++) {
Cell cell = sheet.getRow(i).getCell(region.getLastColumn());
CellStyle cellStyle = cloneCellStyle(sheet, cell);
cellStyle.setBorderRight(borderStyle);
cell.setCellStyle(cellStyle);
}
}
}
以上是关于JAVA Apache POI Excel:为单元格区域添加边框的主要内容,如果未能解决你的问题,请参考以下文章
java poi 导入 excel怎么设置单元格格式为 文字
java用poi读取excel文件时怎么获取每个单元格的列宽?