java利用poi工具导出多行表头,多行表尾的excel表格

表格示例:
在这里插入图片描述
java代码如下:

			public ModelAndView excel(HttpServletRequest request, HttpServletResponse response) throws IOException, ParseException {//需要抛出两个异常
			// 创建excel文件对象
			HSSFWorkbook wb = new HSSFWorkbook();
			// 创建sheet
			Sheet sheet = wb.createSheet("sheet1");
			//表头字体
			Font headerFont = wb.createFont();
			headerFont.setFontName("微软雅黑");
			headerFont.setFontHeightInPoints((short) 18);
			headerFont.setBoldweight(Font.BOLDWEIGHT_NORMAL);
			headerFont.setColor(HSSFColor.BLACK.index);
			//正文字体
			Font contextFont = wb.createFont();
			contextFont.setFontName("微软雅黑");
			contextFont.setFontHeightInPoints((short) 12);
			contextFont.setBoldweight(Font.BOLDWEIGHT_NORMAL);
			contextFont.setColor(HSSFColor.BLACK.index);
			 
			//表头样式,左右上下居中
			CellStyle headerStyle = wb.createCellStyle();
			headerStyle.setFont(headerFont);
			headerStyle.setAlignment(CellStyle.ALIGN_CENTER);// 左右居中
			headerStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);// 上下居中
			headerStyle.setLocked(true);
			headerStyle.setWrapText(false);// 自动换行
			//单元格样式,左右上下居中 边框
			CellStyle commonStyle = wb.createCellStyle();
			commonStyle.setFont(contextFont);
			commonStyle.setAlignment(CellStyle.ALIGN_CENTER);// 左右居中
			commonStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);// 上下居中
			commonStyle.setLocked(true);
			commonStyle.setWrapText(false);// 自动换行
			commonStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN); //下边框
			commonStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);//左边框
			commonStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);//上边框
			commonStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);//右边框
			//单元格样式,左右上下居中 边框
			CellStyle commonWrapStyle = wb.createCellStyle();
			commonWrapStyle.setFont(contextFont);
			commonWrapStyle.setAlignment(CellStyle.ALIGN_CENTER);// 左右居中
			commonWrapStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);// 上下居中
			commonWrapStyle.setLocked(true);
			commonWrapStyle.setWrapText(true);// 自动换行
			commonWrapStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN); //下边框
			commonWrapStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);//左边框
			commonWrapStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);//上边框
			commonWrapStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);//右边框
			//单元格样式,竖向 边框
			CellStyle verticalStyle = wb.createCellStyle();
			verticalStyle.setFont(contextFont);
			verticalStyle.setAlignment(CellStyle.ALIGN_CENTER);// 左右居中
			verticalStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);// 上下居中
			verticalStyle.setRotation((short) 255);//竖向
			verticalStyle.setLocked(true);
			verticalStyle.setWrapText(false);// 自动换行
			verticalStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN); //下边框
			verticalStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);//左边框
			verticalStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);//上边框
			verticalStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);//右边框
			 
			//单元格样式,左右上下居中 无边框
			CellStyle commonStyleNoBorder = wb.createCellStyle();
			commonStyleNoBorder.setFont(contextFont);
			commonStyleNoBorder.setAlignment(CellStyle.ALIGN_CENTER);// 左右居中
			commonStyleNoBorder.setVerticalAlignment(CellStyle.VERTICAL_CENTER);// 上下居中
			commonStyleNoBorder.setLocked(true);
			commonStyleNoBorder.setWrapText(false);// 自动换行
			//单元格样式,左对齐 边框
			CellStyle alignLeftStyle = wb.createCellStyle();
			alignLeftStyle.setFont(contextFont);
			alignLeftStyle.setAlignment(CellStyle.ALIGN_LEFT);// 左对齐
			alignLeftStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);// 上下居中
			alignLeftStyle.setLocked(true);
			alignLeftStyle.setWrapText(false);// 自动换行
			alignLeftStyle.setAlignment(CellStyle.ALIGN_LEFT);// 左对齐
			alignLeftStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN); //下边框
			alignLeftStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);//左边框
			alignLeftStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);//上边框
			alignLeftStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);//右边框
			//单元格样式,左对齐 无边框
			CellStyle alignLeftNoBorderStyle = wb.createCellStyle();
			alignLeftNoBorderStyle.setFont(contextFont);
			alignLeftNoBorderStyle.setAlignment(CellStyle.ALIGN_LEFT);// 左对齐
			alignLeftNoBorderStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);// 上下居中
			alignLeftNoBorderStyle.setLocked(true);
			alignLeftNoBorderStyle.setWrapText(false);// 自动换行
			alignLeftNoBorderStyle.setAlignment(CellStyle.ALIGN_LEFT);// 左对齐
			//单元格样式,右对齐
			CellStyle alignRightStyle = wb.createCellStyle();
			alignRightStyle.setFont(contextFont);
			alignRightStyle.setAlignment(CellStyle.ALIGN_LEFT);// 左对齐
			alignRightStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);// 上下居中
			alignRightStyle.setLocked(true);
			alignRightStyle.setWrapText(false);// 自动换行
			alignRightStyle.setAlignment(CellStyle.ALIGN_RIGHT);// 左对齐
			String fileName = null;
			// 行号
			int rowNum = 0;
			//设置列宽
			for (int i = 0; i < 7; i++) {
			    sheet.setColumnWidth(i, 6000);
			}
			//第一行
			Row r0 = sheet.createRow(rowNum++);
			//行高
			r0.setHeight((short) 800);
			//第一行第一列
			Cell c00 = r0.createCell(0);
			c00.setCellValue("山东省总工会工作人员考勤登记表");
			c00.setCellStyle(headerStyle);
			//合并单元格(从左到右依次:要合并的初始行位置、结束行位置,初始列位置、结束列位置)
			sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 6));
			//考勤时间行
			Row rn = sheet.createRow(rowNum++);
			r0.setHeight((short) 800);
			Cell c01 = rn.createCell(0);
			c01.setCellValue("(考勤月份"+year+"年"+yue+"月)");
			c01.setCellStyle(headerStyle);
			//合并单元格
			sheet.addMergedRegion(new CellRangeAddress(1, 1, 0, 6));
			// 第二行
			Row r1 = sheet.createRow(rowNum++);
			r1.setHeight((short) 500);
			String date =new SimpleDateFormat("yyyy-MM").format(new Date());
			String[] row_first = {"部室(盖章):"+info.getDeptName(), "", "", "", "", "填表时间:", ""};
			for (int i = 0; i < row_first.length; i++) {
			    Cell tempCell = r1.createCell(i);
			    tempCell.setCellStyle(alignLeftNoBorderStyle);
			    if (i == 0) {
			        tempCell.setCellValue(row_first[i]);
			    } else if (i == 5) {
			        tempCell.setCellStyle(alignRightStyle);
			         tempCell.setCellValue(row_first[i]+date.replace("-", "年")+"月");
			    } else {
			        tempCell.setCellValue(row_first[i]);
			    }
			}
			// 合并
			sheet.addMergedRegion(new CellRangeAddress(2, 2, 0, 3));
			sheet.addMergedRegion(new CellRangeAddress(2, 2, 5, 6));
			 
			//第三行
			Row r3 = sheet.createRow(rowNum++);
			r3.setHeight((short) 700);
			String[] row_third = {"姓名", "病假天数", "事假天数", "带薪休假天数", "其他休假天数(需注明何种假)", "旷工天数", "是否销假"};
			for (int i = 0; i < row_third.length; i++) {
			    Cell tempCell = r3.createCell(i);
			    tempCell.setCellValue(row_third[i]);
			    tempCell.setCellStyle(commonWrapStyle);
			}
			//从map中取出 key为list的集合
			List<OutRecord> list=null;
			Map<String, Object> map = this.checkingtotal(info);//调用本类中的方法获得map
			 Iterator<String> iter = map.keySet().iterator();
		        while(iter.hasNext()){
		            String key=iter.next();
		            if(("list").equals(key)) {
		             list = (List<OutRecord>) map.get(key);
		            }
		        }
		        //循环每一行
		        for (OutRecord outrecord : list) {
		        	 Row tempRow = sheet.createRow(rowNum++);
		        	 tempRow.setHeight((short) 500);
		        	  // 循环单元格填入数据
		 		    for (int j = 0; j < 7; j++) {
		 		        Cell tempCell = tempRow.createCell(j);
		 		        tempCell.setCellStyle(commonStyle);
		 		        String tempValue = null;
		 		        if (j == 0) {
		 		            // 姓名
		 		            tempValue = outrecord.getRegistrantName();
		 		        } else if (j == 1) {
		 		            // 病假
		 		            tempValue = outrecord.getBingjia()+"";
		 		        } else if (j == 2) {
		 		            // 事假
		 		            tempValue = outrecord.getShijia()+"";
		 		        } else if (j == 3) {
		 		            // 带薪年假
		 		            tempValue = outrecord.getNianjia()+"";
		 		        } else if (j == 4) {
		 		            // 其他休假
		 		        	if(outrecord.getHunjia()!=null) {
		 		        		tempValue = "婚假:"+outrecord.getHunjia();
		 		        	}
		 		        	if(outrecord.getChanjia()!=null) {
		 		        		tempValue = "产假:"+outrecord.getChanjia();
		 		        	}
		 		        } else if (j == 5) {
		 		            // 旷工天数
		 		        } else {
		 		            // 是否销假
		 		        }
		 		        if(("null").equals(tempValue)) {
		 		        	tempValue="";
		 		        }
		 		        tempCell.setCellValue(tempValue);
		 		    }
				}
			 
			// 注释行
			Row remark = sheet.createRow(rowNum++);
			remark.setHeight((short) 500);
			String[] row_remark = {"注:每月考勤情况应于次月5日前按时报组织部", "", "", "", "", "", ""};
			for (int i = 0; i < row_remark.length; i++) {
			    Cell tempCell = remark.createCell(i);
			    tempCell.setCellStyle(alignLeftNoBorderStyle);
			    tempCell.setCellValue(row_remark[i]);
			}
			int remarkRowNum = list.size() + 4;
			// 合并
			sheet.addMergedRegion(new CellRangeAddress(remarkRowNum, remarkRowNum, 0, 6));
			 
			// 尾行
			Row foot = sheet.createRow(rowNum++);
			foot.setHeight((short) 500);
			String[] row_foot = {"考勤人员:", "", "", "", "", "部室主要负责人:", ""};
			for (int i = 0; i < row_foot.length; i++) {
			    Cell tempCell = foot.createCell(i);
			    tempCell.setCellStyle(alignLeftNoBorderStyle);
			    if (i == 0) {
			        tempCell.setCellValue(row_foot[i]);
			    }  else if (i == 5) {
			        tempCell.setCellValue(row_foot[i] );
			    } else {
			        tempCell.setCellValue(row_foot[i]);
			    }
			}
			int footRowNum = list.size() + 5;
			// 合并
			sheet.addMergedRegion(new CellRangeAddress(footRowNum, footRowNum, 0, 1));
			sheet.addMergedRegion(new CellRangeAddress(footRowNum, footRowNum, 5, 6));
		 
		    fileName = " 工作人员考勤登记表.xls";
		  //输出Excel文件  
			OutputStream stream = response.getOutputStream();  
		    response.reset();
		 // 处理文件名包含特殊字符出现的乱码问题
		 String userAgent = request.getHeader("User-Agent");
		 if (StringUtils.isNotBlank(userAgent)) {
		     userAgent = userAgent.toLowerCase();
		     if (userAgent.contains("msie") || userAgent.contains("trident") || userAgent.contains("edge")) {
		         if (fileName.length() > 150) {// 解决IE 6.0问题
		             fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
		         } else {
		             fileName = URLEncoder.encode(fileName, "UTF-8");
		         }
		     } else {
		         fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
		     }
		 }
		 	response.setHeader("Content-disposition", "attachment;filename=\"" + fileName + "\"");
		 	response.setContentType("application/vnd.ms-excel");         
		    wb.write(stream);  
		    stream.close(); 
			}

另附本次用poi的jar包:
在这里插入图片描述

  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java中实现多行表头导出Excel可以使用Apache POI库。下面是一个简单的示例代码,其中包括三个表头行和两个数据行: ```java import java.io.FileOutputStream; import java.io.IOException; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.IndexedColors; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class ExcelExporter { public static void export(String[][] data) throws IOException { Workbook workbook = new XSSFWorkbook(); Sheet sheet = workbook.createSheet("Sheet1"); // 创建表头行1 Row headerRow1 = sheet.createRow(0); CellStyle headerStyle1 = workbook.createCellStyle(); headerStyle1.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex()); headerStyle1.setFillPattern(CellStyle.SOLID_FOREGROUND); // 设置表头行高 headerRow1.setHeightInPoints(30); // 创建表头单元格 for (int i = 0; i < data[0].length; i++) { Cell cell = headerRow1.createCell(i); cell.setCellValue(data[0][i]); cell.setCellStyle(headerStyle1); } // 合并表头行1 sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 2)); // 创建表头行2 Row headerRow2 = sheet.createRow(1); CellStyle headerStyle2 = workbook.createCellStyle(); headerStyle2.setFillForegroundColor(IndexedColors.GREY_40_PERCENT.getIndex()); headerStyle2.setFillPattern(CellStyle.SOLID_FOREGROUND); // 设置表头行高 headerRow2.setHeightInPoints(30); // 创建表头单元格 Cell cell = headerRow2.createCell(0); cell.setCellValue("Header 1"); cell.setCellStyle(headerStyle2); cell = headerRow2.createCell(1); cell.setCellValue("Header 2"); cell.setCellStyle(headerStyle2); cell = headerRow2.createCell(2); cell.setCellValue("Header 3"); cell.setCellStyle(headerStyle2); // 合并表头行2 sheet.addMergedRegion(new CellRangeAddress(1, 2, 0, 0)); sheet.addMergedRegion(new CellRangeAddress(1, 1, 1, 2)); // 创建表头行3 Row headerRow3 = sheet.createRow(2); CellStyle headerStyle3 = workbook.createCellStyle(); headerStyle3.setFillForegroundColor(IndexedColors.GREY_40_PERCENT.getIndex()); headerStyle3.setFillPattern(CellStyle.SOLID_FOREGROUND); // 设置表头行高 headerRow3.setHeightInPoints(30); // 创建表头单元格 cell = headerRow3.createCell(1); cell.setCellValue("Sub Header 1"); cell.setCellStyle(headerStyle3); cell = headerRow3.createCell(2); cell.setCellValue("Sub Header 2"); cell.setCellStyle(headerStyle3); // 创建数据行 for (int i = 0; i < data.length - 1; i++) { Row dataRow = sheet.createRow(i + 3); for (int j = 0; j < data[i + 1].length; j++) { Cell dataCell = dataRow.createCell(j); dataCell.setCellValue(data[i + 1][j]); } } // 调整列宽 for (int i = 0; i < data[0].length; i++) { sheet.autoSizeColumn(i); } // 导出Excel文件 FileOutputStream outputStream = new FileOutputStream("output.xlsx"); workbook.write(outputStream); workbook.close(); outputStream.close(); } } ``` 其中,`data`是一个二维数组,第一行是表头,其余行是数据。在代码中,我们创建了三个表头行,分别为“Header 1”、“Header 2”和“Sub Header 1/Sub Header 2”。我们使用`sheet.addMergedRegion`方法将单元格合并以创建多行表头。最后,我们将数据写入Excel文件并导出。你可以根据实际需求修改代码。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值