做统计报表功能的时候,想要做出好看的表格,经常要进行“合并单元格”操作。小编今天提供一个通用的方法,就能快速地完成啦!
private void mergeCell(XSSFSheet sheet, int firstRow, int lastRow, int firstCol, int lastCol, String cellValue, Boolean isBold) {
XSSFWorkbook workBook = sheet.getWorkbook();
// 标题行样式
XSSFFont blodFont = workBook.createFont();
blodFont.setBold(true);
XSSFCellStyle headerStyle = workBook.createCellStyle();
if(isBold) { //是否加粗
headerStyle.setFont(blodFont); // 设置字体
headerStyle.setFillBackgroundColor(HSSFColor.LIGHT_GREEN.index); //设置背景色
headerStyle.setFillForegroundColor(HSSFColor.LIGHT_GREEN.index);// 设置前景色
headerStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
}
headerStyle.setAlignment(HorizontalAlignment.CENTER); // 水平对齐
headerStyle.setVerticalAlignment(VerticalAlignment.CENTER);
headerStyle.setBorderBottom(CellStyle.BORDER_THIN); // 下边框
headerStyle.setBorderLeft(CellStyle.BORDER_THIN);// 左边框
headerStyle.setBorderTop(CellStyle.BORDER_THIN);// 上边框
headerStyle.setBorderRight(CellStyle.BORDER_THIN);// 右边框
if(!(firstRow == lastRow && firstCol == lastCol)){
CellRangeAddress address = new CellRangeAddress(firstRow, lastRow, firstCol, lastCol);
sheet.addMergedRegion(address);
RegionUtil.setBorderBottom(1, address, sheet, workBook);
RegionUtil.setBorderLeft(1, address, sheet, workBook);
RegionUtil.setBorderRight(1, address, sheet, workBook);
RegionUtil.setBorderTop(1, address, sheet, workBook);
}
XSSFRow row = null;
if(sheet.getRow(firstRow) != null) {
row = sheet.getRow(firstRow);
}else {
row = sheet.createRow(firstRow);
}
XSSFCell cell = row.createCell(firstCol);
cell.setCellStyle(headerStyle);
cell.setCellValue(cellValue);
}
那么,怎么调用呢?
public String exportExcel(HttpServletRequest request) {
String path = request.getAttribute("path").toString();
String title = "临时";
FileOutputStream outputStream = null;
try {
if (request.getParameter("title") != null) {
title = request.getParameter("title");
}
// 临时xlsx文件存储路径
path += "\\" + title + ".xlsx";
File file = new File(path);
File fileParent = file.getParentFile();
if(!fileParent.exists()){
fileParent.mkdirs();
}
file.createNewFile();
// 创建工作簿
XSSFWorkbook workBook = new XSSFWorkbook();
XSSFSheet sheetHz = workBook.createSheet("记录");
mergeCell(sheet,1,3,0,0,"名称", true);
outputStream = new FileOutputStream(new File(path));
workBook.write(outputStream);
workBook.close();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
return title + ".xlsx";
}