今天用POI導(dǎo)出Excel的時(shí)候,發(fā)現(xiàn)導(dǎo)出的單元格確少邊框,最后發(fā)現(xiàn)有2個(gè)方案可以解決。文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-621720.html
方案一
CellRangeAddress的4個(gè)參數(shù)分別表示:起始行號(hào),終止行號(hào), 起始列號(hào),終止列號(hào)文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-621720.html
// 使用這種方式合并單元格時(shí),要給單元格逐一設(shè)置帶邊框的樣式
sheet.addMergedRegion(new CellRangeAddress(1, 1, 1, 3));
// 例如:
HSSFCellStyle defaultStyle = ExportToExcelUtil.setDefaultStyle(workbook);
// 為單元格設(shè)置帶邊框的樣式
setCellStyles(row, 2, 3, defaultStyle );
/**
* 設(shè)置單元格樣式
*/
private void setCellStyles(HSSFRow row, int start, int end, HSSFCellStyle cellStyle) {
for (int i = start; i <= end; i++) {
cell = row.createCell(i);
cell.setCellStyle(cellStyle);
}
}
/**
* 帶邊框的樣式+
*/
public static HSSFCellStyle setDefaultStyle(HSSFWorkbook workbook) {
HSSFCellStyle cellStyle = workbook.createCellStyle();
// 邊框
cellStyle.setBorderBottom(BorderStyle.THIN);
cellStyle.setBorderLeft(BorderStyle.THIN);
cellStyle.setBorderRight(BorderStyle.THIN);
cellStyle.setBorderTop(BorderStyle.THIN);
return cellStyle;
}
方案二
// 合并單元格
CellRangeAddress region = new CellRangeAddress(1, 1, 2, 2);
sheet.addMergedRegion(region);
// 合并之后為合并的單元格設(shè)置樣式
setRegionStyle(sheet, region, defaultStyle);
/**
* 為合并的單元格設(shè)置樣式(可根據(jù)需要自行調(diào)整)
*/
@SuppressWarnings("deprecation")
public static void setRegionStyle(HSSFSheet sheet, CellRangeAddress region, HSSFCellStyle cs) {
for (int i = region.getFirstRow(); i <= region.getLastRow(); i++) {
HSSFRow row = sheet.getRow(i);
if (null == row) row = sheet.createRow(i);
for (int j = region.getFirstColumn(); j <= region.getLastColumn(); j++) {
HSSFCell cell = row.getCell(j);
if (null == cell) cell = row.createCell(j);
cell.setCellStyle(cs);
}
}
}
到了這里,關(guān)于Java POI導(dǎo)出Excel時(shí),合并單元格沒(méi)有邊框的問(wèn)題的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!