欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

导出标题,表头合并单元格

程序员文章站 2022-06-14 09:10:48
...

导出标题,表头合并单元格

1,原标题,表头导出样式

标题样式
导出标题,表头合并单元格表头样式
导出标题,表头合并单元格

2,现期望样式

导出标题,表头合并单元格

3,步骤如下

1. 业务层

public void exportOffsetResult(HttpServletResponse response, RedirectAttributes redirectAttributes, StuPaycostOwe records) {

		List<StuPaycostOwe> findListRecords = findListRecords(records);
		if(!findListRecords.isEmpty()) {
			String fileName=findListRecords.get(0).getGrade()+"导入反馈"+DateUtils.getDate("yyyy年MM月dd日 HH时mm分ss秒");
			List<Map<String, Object>> resultLM = createExcelMsg(findListRecords);
			List< List<String>> listStr=Lists.newArrayList();//表头的List集合
   	        List<Integer> intRow=Lists.newArrayList();//存放那些行不需要添加背景填充和数据行格式一样如果不需要则置为空list
   	        intRow.add(0);
   	        //设置表头数据
   	        List<String>  li0=Lists.newArrayList();
	    	List<String>  li1=Lists.newArrayList();
	    	List<String>  li2=Lists.newArrayList();
	    	//设置需要取值的键值`在这里插入代码片`
	    	List<String>  liKey=Lists.newArrayList();
	    	//设置需要合并的单元格
	    	List<String>  rli=Lists.newArrayList();
	    	rli.add("1,2,0,0");
	    	rli.add("1,2,1,1");
	    	rli.add("1,2,2,2");
	    	rli.add("1,2,3,3");
	    	rli.add("1,2,4,4");
	    	rli.add("1,2,5,5");
	    	rli.add("1,2,6,6");
	    	rli.add("1,2,7,7");
	    	rli.add("1,2,8,8");
	    	rli.add("1,2,9,9");
	    	rli.add("1,2,10,10");
	    	rli.add("1,2,11,11");
	    	rli.add("1,2,12,12");
	    	rli.add("1,2,13,13");
	    	rli.add("1,2,14,14");
	    	rli.add("1,2,15,15");
	    	rli.add("1,2,16,16");
	    	rli.add("1,2,17,17");
	    	li0.add(fileName);
	    	li1.add("序号");li2.add("");
	    	li1.add("学年");li2.add("");
	    	li1.add("年级");li2.add("");
	    	li1.add("院系");li2.add("");
	    	li1.add("专业");li2.add("");
	    	li1.add("班级");li2.add("");
	    	li1.add("学生姓名");li2.add("");
	    	li1.add("学号");li2.add("");
	    	li1.add("考生号");li2.add("");
	    	li1.add("身份证号");li2.add("");
	    	li1.add("学生类型");li2.add("");
	    	li1.add("宿舍类型");li2.add("");
	    	li1.add("助学贷款");li2.add("");
	    	li1.add("建档立卡");li2.add("");
	    	li1.add("缓缴金额");li2.add("");
	    	li1.add("应缴金额");li2.add("");
	    	li1.add("实缴金额");li2.add("");
	    	li1.add("欠费金额");li2.add("");
	    	List<NewCostTuitionFees> payDetails = findListRecords.get(0).getPayDetails();
	    	rli.add("1,1,18,"+(payDetails.size()+18-1)+"");
	    	for (int i = 0; i < payDetails.size(); i++) {
	    		li2.add(payDetails.get(i).getCostName());
	    		if(i == 0) {
	    			li1.add("缴费明细");
	    		}else {
	    			li1.add("");
	    		}
			}
	    	List<ChargeWay> payMethods = findListRecords.get(0).getPayMethods();
	    	rli.add("1,1,"+(payDetails.size()+18)+","+(payDetails.size()+18+payMethods.size()-1)+"");
	    	for (int i = 0; i < payMethods.size(); i++) {
	    		li2.add(payMethods.get(i).getChargeName());
	    		if(i == 0) {
	    			li1.add("缴费方式");
	    		}else {
	    			li1.add("");
	    		}
			}
	    	rli.add("0,0,0,"+(18+payDetails.size()+payDetails.size()-1)+"");
	    	liKey.add("orderNumber");
	    	liKey.add("year");
	    	liKey.add("grade");
	    	liKey.add("deptName");
	    	liKey.add("majorName");
	    	liKey.add("className");
	    	liKey.add("stuName");
	    	liKey.add("stuNumber");
	    	liKey.add("examNumber");
	    	liKey.add("idCard");
	    	liKey.add("enrollTypeName");
	    	liKey.add("dormTypeName");
	    	liKey.add("dk");
	    	liKey.add("jm");
	    	liKey.add("hj");
	    	liKey.add("needFee");
	    	liKey.add("isFee");
	    	liKey.add("owefee");
	    	 List<NewCostTuitionFees> payDetails2 = findListRecords.get(0).getPayDetails();
	            for (int i = 0; i < payDetails2.size(); i++) {
	            	liKey.add("payDetail"+i);
				}
	            List<ChargeWay> payMethods2 = findListRecords.get(0).getPayMethods();
	            for (int i = 0; i < payMethods2.size(); i++) {
	            	liKey.add("payMethods"+i);
				}
	    	listStr.add(li0);
	   	    listStr.add(li1);
	   	    listStr.add(li2);
	    	try {
				export(response, fileName, resultLM, liKey, rli,listStr,intRow);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
	}
`/**
	 * 整理导出数据
	 * @param fosList
	 * @return
	 */
	private List<Map<String, Object>> createExcelMsg(List<StuPaycostOwe> fosList) {
		List<Map<String, Object>> listmap = new ArrayList<Map<String, Object>>();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("sheetName", "sheet1");
        listmap.add(map);
        for (int j = 0; j < fosList.size(); j++) {
        	StuPaycostOwe fof=fosList.get(j);
        	if(fof != null){
	            Map<String, Object> mapValue = new HashMap<String, Object>();
	            mapValue.put("orderNumber",j+1);
	            mapValue.put("year",fof.getYear());
	            mapValue.put("grade",fof.getGrade());
	            mapValue.put("deptName",fof.getDeptName());
	            mapValue.put("majorName",fof.getMajorName());
	            mapValue.put("className",fof.getClassName());
	            mapValue.put("stuName",fof.getStuName());
	            mapValue.put("stuNumber",fof.getStuNumber());
	            mapValue.put("examNumber",fof.getExamNumber());
	            mapValue.put("idCard",fof.getIdCard());
	            mapValue.put("enrollTypeName",fof.getEnrollTypeName());
	            mapValue.put("dormTypeName",fof.getDormTypeName());
	            mapValue.put("dk",fof.getDk());
	            mapValue.put("jm",fof.getJm());
	            mapValue.put("hj",fof.getHj());
	            mapValue.put("needFee",fof.getNeedFee());
	            mapValue.put("isFee",Double.parseDouble(fof.getIsFee()));
	            mapValue.put("owefee",fof.getNeedFee()-Double.parseDouble(fof.getIsFee()));
	            
	            List<NewCostTuitionFees> payDetails = fof.getPayDetails();
	            for (int i = 0; i < payDetails.size(); i++) {
	            	if(StringUtils.isEmpty(payDetails.get(i).getCostFees())) {
	            		mapValue.put("payDetail"+i,payDetails.get(i).getCostFees());
	            	}else {
	            		mapValue.put("payDetail"+i,Double.parseDouble(payDetails.get(i).getCostFees()));
	            	}
				}
	            List<ChargeWay> payMethods = fof.getPayMethods();
	            for (int i = 0; i < payMethods.size(); i++) {
	            	if(StringUtils.isEmpty(payMethods.get(i).getFees())) {
	            		mapValue.put("payMethods"+i,payMethods.get(i).getFees());
	            	}else {
	            		mapValue.put("payMethods"+i,Double.parseDouble(payMethods.get(i).getFees()));
	            	}
				}
	          
	            listmap.add(mapValue);
        	}
        }
        return listmap;
	}
		  /**
	    * headRowNum 有多少个headRowParam 就必须要有多少组  {"1,2,3,4"} // 1起始行, 2终止行, 3起始列, 4终止列
	    * @param response
	    * @param fileName
	    * @param list
	    * @param keys
	    * @param headRange {"1,2,3,4"} // 1起始行, 2终止行, 3起始列, 4终止列
	    * @param headRowNum
	    * @param headRowParam
	    * @throws IOException
	    */
		private void export(HttpServletResponse response, String fileName, List<Map<String, Object>> list,List<String> keys,List<String> headRange,List<List<String>> headRowParam,List<Integer> intRow) throws IOException {
			ByteArrayOutputStream os = new ByteArrayOutputStream();
	        try {
	        	CwReportExcleUtils.createCustomWorkBook(list,keys,headRange,headRowParam,intRow).write(os);
	        } catch (IOException e) {
	            e.printStackTrace();
	        }
	        byte[] content = os.toByteArray();
	        InputStream is = new ByteArrayInputStream(content);
	        // 设置response参数,可以打开下载页面
	        response.reset();
	        response.setContentType("application/vnd.ms-excel;charset=utf-8");
	        response.setHeader("Content-Disposition", "attachment;filename="+ new String((fileName + ".xls").getBytes(), "iso-8859-1"));
	        ServletOutputStream out = response.getOutputStream();
	        BufferedInputStream bis = null;
	        BufferedOutputStream bos = null;
	        try {
	            bis = new BufferedInputStream(is);
	            bos = new BufferedOutputStream(out);
	            byte[] buff = new byte[2048];
	            int bytesRead;
	            // Simple read/write loop.
	            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
	                bos.write(buff, 0, bytesRead);
	            }
	        } catch (final IOException e) {
	            throw e;
	        } finally {
	            if (bis != null)
	                bis.close();
	            if (bos != null)
	                bos.close();
	        }
		}

 2. 工具类
 package com.bigdata.campus.report.utils;

import java.util.List;
import java.util.Map;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.DataFormat;
import org.apache.poi.ss.usermodel.Font;
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.ss.util.CellRangeAddress;

public class CwReportExcleUtils {
		/**
		 * Excel的导出(自定义表头)
		 * @describe list 为数据 keys 为需要显示在excel中的参数对应的值,因为是用map存的,放的都是对应的key</br>
		 * headRange 合并表头的参数 如new String[] { "0,0,0,2", "0,0,0,2", "3,3,4,4","3,3,5,5" }; 起始行, 终止行, 起始列, 终止列</br>
		 * headRowParam 合并表头的参数(数量与headRowNum对应)
		 * intRow存放那些行不需要添加背景填充和数据行格式一样如果不需要则置为空list
		 * @param list
		 * @param keys
		 * @param columnNames
		 * @param headRowNum
		 * @param headRange
		 * @param rowParam
		 * @return
		 */
		 public static Workbook createCustomWorkBook(
													 List<Map<String, Object>> list,
													 List<String> keys,
													 List<String> headRange,
													 List<List<String>> ListStr,
													 List<Integer> intRow
													 ) {
			 // 创建excel工作簿
			 Workbook wb = new HSSFWorkbook();
			 // 创建第一个sheet(页),并命名
			 Sheet sheet = wb.createSheet(list.get(0).get("sheetName").toString());
			 // 手动设置列宽。第一个参数表示要为第几列设;,第二个参数表示列的宽度,n为列高的像素数。
			 for(int i=0;i<keys.size();i++){
				 sheet.setColumnWidth((short) i, (short) (37.5 * 150));
			 }
			// 创建两种单元格格式
			 CellStyle cs1_title   = createCellStyle_title(wb);//标题样式
			 CellStyle cs1_Head   = createCellStyle_Head(wb);//表头样式
			 CellStyle cs2_Double = createCellStyle_Double(wb);//Double格式
			 CellStyle cs3_String = createCellStyle_String(wb);//String格式
			 CellStyle cs4_Int = createCellStyle_Int(wb);//int格式
			 CellStyle cs5_left  = createCellStyle_left(wb);//居左样式
			 // 循环创建表头
			 int headRowNum=ListStr.size();
			 for(int i=0;i<headRowNum;i++){
				 Row row = sheet.createRow((short) i);
				 if(i==0){//标题
					 row.setHeight((short) (5 * 150));
					 for(int j=0;j<ListStr.get(i).size();j++){
						 Cell cell = row.createCell(j);
						 String param=ListStr.get(i).get(j);
						 cell.setCellValue(param);
						 cell.setCellStyle(cs1_title);
					 }
				 }else if(intRow.contains(i)){//表头
					 row.setHeight((short) (4 * 150));
					 for(int j=0;j<ListStr.get(i).size();j++){
						 String param=ListStr.get(i).get(j);
						 Cell cell = row.createCell(j);
						 cell.setCellValue(param);
						 cell.setCellStyle(cs5_left);
					 }
				 }else{//表头
					 row.setHeight((short) (4 * 150));
					 for(int j=0;j<ListStr.get(i).size();j++){
						 String param=ListStr.get(i).get(j);
						 Cell cell = row.createCell(j);
						 cell.setCellValue(param);
						 cell.setCellStyle(cs1_Head);
					 }
				 }
			 }
			//动态合并单元格
	         for (int i = 0; i < headRange.size(); i++) {
	            String[] temp = headRange.get(i).split(",");
	            Integer startrow = Integer.parseInt(temp[0]);
	            Integer overrow = Integer.parseInt(temp[1]);
	            Integer startcol = Integer.parseInt(temp[2]);
	            Integer overcol = Integer.parseInt(temp[3]);
	            sheet.addMergedRegion(new CellRangeAddress(startrow, overrow,startcol, overcol));// 起始行, 终止行, 起始列, 终止列
	         }
			 //设置每行每列的值
			 for (short i = 1; i < list.size(); i++) {
				 // Row 行,Cell 方格 , Row 和 Cell 都是从0开始计数的
				 // 创建一行,在页sheet上
				 Row row1 = sheet.createRow((short) i+headRowNum-1);
				 row1.setHeight((short) (3 * 150));
				 // 在row行上创建一个方格
				 for(short j=0;j<keys.size();j++){
					 Cell cell = row1.createCell(j);
					 if(list.get(i).get(keys.get(j)) instanceof Double){
						 Double d=Double.parseDouble(list.get(i).get(keys.get(j)) == null?"0": list.get(i).get(keys.get(j)).toString());
						 cell.setCellValue(d);
						 cell.setCellStyle(cs2_Double);
					 }else if(list.get(i).get(keys.get(j)) instanceof Integer){
						 Integer it=Integer.parseInt(list.get(i).get(keys.get(j)) == null?"0": list.get(i).get(keys.get(j)).toString());
						 cell.setCellValue(it);
						 cell.setCellStyle(cs4_Int);
					 }else{
						 cell.setCellValue(list.get(i).get(keys.get(j)) == null?" ": list.get(i).get(keys.get(j)).toString());
						 cell.setCellType(Cell.CELL_TYPE_STRING);
						 cell.setCellStyle(cs3_String);
					 }
				 }
			 }
			 return wb;
		 }
		 /**
		  * 居左样式
		  * @param wb
		  * @return
		  */
		 private static CellStyle createCellStyle_left(Workbook wb) {
			// 创建单元格格式
			 CellStyle csleft = wb.createCellStyle();
			// 创建字体
			 Font f = wb.createFont();
			// 创建字体样式(用于列名)
			 f.setFontHeightInPoints((short) 12);
			 f.setColor(IndexedColors.BLACK.getIndex());
			 f.setBoldweight(Font.BOLDWEIGHT_BOLD);
			 // 设置单元格的样式(用于列名)
			 csleft.setFont(f);
			 csleft.setBorderLeft(CellStyle.BORDER_THIN);
			 csleft.setBorderRight(CellStyle.BORDER_THIN);
			 csleft.setBorderTop(CellStyle.BORDER_THIN);
			 csleft.setBorderBottom(CellStyle.BORDER_THIN);
			 csleft.setAlignment(CellStyle.ALIGN_LEFT);//水平居左
			 csleft.setVerticalAlignment(CellStyle.VERTICAL_CENTER);//垂直居中
			return csleft;
		}
		/**
		  * 标题样式
		  * @param wb
		  * @return
		  */
		 private static CellStyle createCellStyle_title(Workbook wb) {
			// 创建单元格格式
			 CellStyle csTitle = wb.createCellStyle();
			// 创建字体
			 Font f = wb.createFont();
			// 创建字体样式(用于列名)
			 f.setFontHeightInPoints((short) 18);
			 f.setColor(IndexedColors.BLACK.getIndex());
			 f.setBoldweight(Font.BOLDWEIGHT_BOLD);
			 // 设置单元格的样式(用于列名)
			 csTitle.setFont(f);
			 csTitle.setBorderLeft(CellStyle.BORDER_THIN);
			 csTitle.setBorderRight(CellStyle.BORDER_THIN);
			 csTitle.setBorderTop(CellStyle.BORDER_THIN);
			 csTitle.setBorderBottom(CellStyle.BORDER_THIN);
			 csTitle.setAlignment(CellStyle.ALIGN_CENTER);//水平居中
			 csTitle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);//垂直居中
			return csTitle;
		}
		/**
		  * 整型格式样式
		  * @param wb
		  * @return
		  */
		private static CellStyle createCellStyle_Int(Workbook wb) {
			// 创建单元格格式
			CellStyle cs4 = wb.createCellStyle();
			// 创建字体
			Font f4 = wb.createFont();
			// 创建第二种字体样式(用于值)
			f4.setFontHeightInPoints((short) 12);
			f4.setColor(IndexedColors.BLACK.getIndex());
			// 设置第二种单元格的样式(用于值)
			cs4.setFont(f4);
			cs4.setBorderLeft(CellStyle.BORDER_THIN);
			cs4.setBorderRight(CellStyle.BORDER_THIN);
			cs4.setBorderTop(CellStyle.BORDER_THIN);
			cs4.setBorderBottom(CellStyle.BORDER_THIN);
			cs4.setAlignment(CellStyle.ALIGN_CENTER);
			cs4.setVerticalAlignment(CellStyle.VERTICAL_CENTER);//垂直居中
			DataFormat df = wb.createDataFormat();  //此处设置数据格式  
			cs4.setDataFormat(df.getFormat("#0")); //数据格式只显示整数,如果是小数点后保留两位,可以写contentStyle.setDataFormat(df.getFormat("#,#0.00"));  
			return cs4;
		}
		/**
		 * 普通文本格式
		 * @param wb
		 * @return
		 */
		private static CellStyle createCellStyle_String(Workbook wb) {
			// 创建单元格格式
			 CellStyle cs3 = wb.createCellStyle();
			 // 创建字体
			 Font f2 = wb.createFont();
			 // 创建第二种字体样式(用于值)
			 f2.setFontHeightInPoints((short) 12);
			 f2.setColor(IndexedColors.BLACK.getIndex());
			 // 设置第二种单元格的样式(用于值)
			 cs3.setFont(f2);
			 cs3.setBorderLeft(CellStyle.BORDER_THIN);
			 cs3.setBorderRight(CellStyle.BORDER_THIN);
			 cs3.setBorderTop(CellStyle.BORDER_THIN);
			 cs3.setBorderBottom(CellStyle.BORDER_THIN);
			 cs3.setAlignment(CellStyle.ALIGN_CENTER);
			 cs3.setVerticalAlignment(CellStyle.VERTICAL_CENTER);//垂直居中
			 DataFormat df = wb.createDataFormat();  //此处设置数据格式  
			 cs3.setDataFormat(df.getFormat("@")); //数据格式只显示整数,如果是小数点后保留两位,可以写contentStyle.setDataFormat(df.getFormat("#,#0.00"));  
			return cs3;
		}
		/**
		 * 数字格式(保留两位小数)
		 * @param wb
		 * @return
		 */
		private static CellStyle createCellStyle_Double(Workbook wb) {
			// 创建单元格格式
			CellStyle cs2 = wb.createCellStyle();
			// 创建字体
			Font f2 = wb.createFont();
			// 创建第二种字体样式(用于值)
			f2.setFontHeightInPoints((short) 12);
			f2.setColor(IndexedColors.BLACK.getIndex());
			// 设置第二种单元格的样式(用于值)
			cs2.setFont(f2);
			cs2.setBorderLeft(CellStyle.BORDER_THIN);
			cs2.setBorderRight(CellStyle.BORDER_THIN);
			cs2.setBorderTop(CellStyle.BORDER_THIN);
			cs2.setBorderBottom(CellStyle.BORDER_THIN);
			cs2.setAlignment(CellStyle.ALIGN_CENTER);
			cs2.setVerticalAlignment(CellStyle.VERTICAL_CENTER);//垂直居中
			DataFormat df = wb.createDataFormat();  //此处设置数据格式  
			cs2.setDataFormat(df.getFormat("#,#0.00")); //数据格式只显示整数,如果是小数点后保留两位,可以写contentStyle.setDataFormat(df.getFormat("#,#0.00"));  
			return cs2;
		}
		/**
		 * 表头样式
		 * @param wb
		 * @return
		 */
		private static CellStyle createCellStyle_Head(Workbook wb) {
			// 创建单元格格式
			 CellStyle cs = wb.createCellStyle();
			// 创建字体
			 Font f = wb.createFont();
			// 创建字体样式(用于列名)
			 f.setFontHeightInPoints((short) 12);
			 f.setColor(IndexedColors.BLACK.getIndex());
			 f.setBoldweight(Font.BOLDWEIGHT_BOLD);
			 // 设置单元格的样式(用于列名)
			 cs.setFont(f);
			 cs.setBorderLeft(CellStyle.BORDER_THIN);
			 cs.setBorderRight(CellStyle.BORDER_THIN);
			 cs.setBorderTop(CellStyle.BORDER_THIN);
			 cs.setBorderBottom(CellStyle.BORDER_THIN);
			 cs.setAlignment(CellStyle.ALIGN_CENTER);//水平居中
			 cs.setVerticalAlignment(CellStyle.VERTICAL_CENTER);//垂直居中
			 cs.setFillForegroundColor(IndexedColors.PALE_BLUE.index);
			 cs.setFillPattern(CellStyle.SOLID_FOREGROUND);
			return cs;
		}
}
相关标签: 导出合并列