Java根据注解导出数据到Excel

利用注解 + 反射优雅的实现通用 Excel 导入导出(通用版附源码) 看完美团、字节、腾讯这三家的一二三面试问题,是不是感觉问的特别多,可能咱们真的又得开启面试造火箭、工作拧螺丝的模式去准备下一次的面试了。开篇有提及我可是足足背下了Java互联网工程师面试1000题,多少还是有点用的呢,换汤不换药,不管面试官怎么问你,抓住本质即可!能读到此处的都是真爱Java互联网工程师面试1000题。 阅读详情
  1. 开发背景win10专业版、eclipse4.7.3a、Junit5
  2. 建立一个maven工程,pom文件如下:
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0</modelVersion>
      <groupId>com.szcatic</groupId>
      <artifactId>export</artifactId>
      <version>0.0.1-SNAPSHOT</version>
      <dependencies>
      	<!-- junit5运行所需jar包 -->
    	<dependency>
    	    <groupId>org.junit.jupiter</groupId>
    	    <artifactId>junit-jupiter-engine</artifactId>
    	    <version>5.2.0</version>
    	    <scope>test</scope>
    	</dependency>
    	<dependency>
    	    <groupId>org.junit.platform</groupId>
    	    <artifactId>junit-platform-runner</artifactId>
    	    <version>1.2.0</version>
    	    <scope>test</scope>
    	</dependency>
    	<!-- 导出所需jar包 -->
    	<dependency>
    	    <groupId>org.apache.poi</groupId>
    	    <artifactId>poi</artifactId>
    	    <version>3.17</version>
    	    <exclusions>
    	    	<exclusion>
    	    		<groupId>org.apache.commons</groupId>
    	    		<artifactId>commons-collections4</artifactId>
    	    	</exclusion>
    	    </exclusions>
    	</dependency>
    	<dependency>
    	    <groupId>org.apache.commons</groupId>
    	    <artifactId>commons-collections4</artifactId>
    	    <version>4.2</version>
    	    <exclusions>
    	    	<exclusion>
    	    		<groupId>junit</groupId>
    	    		<artifactId>junit</artifactId>
    	    	</exclusion>
    	    </exclusions>
    	</dependency>
    	<dependency>
    	    <groupId>org.apache.poi</groupId>
    	    <artifactId>poi-ooxml</artifactId>
    	    <version>3.17</version>
    	</dependency>
    	<!--Lists.newArrayList()所在工具类 -->
    	<dependency>
    	    <groupId>com.google.guava</groupId>
    	    <artifactId>guava</artifactId>
    	    <version>26.0-jre</version>
    	</dependency>
    	<dependency>
    	    <groupId>javax.servlet</groupId>
    	    <artifactId>javax.servlet-api</artifactId>
    	    <version>4.0.1</version>
    	    <scope>provided</scope>
    	</dependency>
    	<!-- log4j2所需jar包 -->
    	<dependency>
    	    <groupId>org.apache.logging.log4j</groupId>
    	    <artifactId>log4j-api</artifactId>
    	    <version>2.11.0</version>
    	</dependency>
    	<dependency>
    	    <groupId>org.apache.logging.log4j</groupId>
    	    <artifactId>log4j-core</artifactId>
    	    <version>2.11.0</version>
    	</dependency>
    	<dependency>
    	    <groupId>org.apache.logging.log4j</groupId>
    	    <artifactId>log4j-slf4j-impl</artifactId>
    	    <version>2.11.0</version>
    	</dependency>
    	<dependency>
    	    <groupId>org.slf4j</groupId>
    	    <artifactId>slf4j-api</artifactId>
    	    <version>1.7.25</version>
    	</dependency>
      </dependencies>
    </project>

     

  3. 定义注解接口
    package com.szcatic.service;
    
    import java.lang.annotation.ElementType;
    import java.lang.annotation.Retention;
    import java.lang.annotation.RetentionPolicy;
    import java.lang.annotation.Target;
    
    /**
     * Excel注解定义
     * @author zsx
     * @version 2018-09-26
     */
    @Target({ElementType.METHOD, ElementType.FIELD, ElementType.TYPE})
    @Retention(RetentionPolicy.RUNTIME)
    public @interface ExcelField {
    
    	/**
    	 * 导出字段标题
    	 */
    	String title();
    	
    	
    	/**
    	 * 导出字段字段排序(升序)
    	 */
    	int sort() default 0;
    
    }
    

     

  4. 导出工具类
    package com.szcatic.util;
    
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.OutputStream;
    import java.io.UnsupportedEncodingException;
    import java.lang.annotation.Annotation;
    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    import java.text.SimpleDateFormat;
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Comparator;
    import java.util.Date;
    import java.util.List;
    import java.util.Map;
    import java.util.Map.Entry;
    
    import javax.servlet.http.HttpServletResponse;
    
    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.Font;
    import org.apache.poi.ss.usermodel.HorizontalAlignment;
    import org.apache.poi.ss.usermodel.Row;
    import org.apache.poi.ss.usermodel.Sheet;
    import org.apache.poi.ss.usermodel.VerticalAlignment;
    import org.apache.poi.ss.usermodel.Workbook;
    import org.apache.poi.ss.util.CellRangeAddress;
    import org.apache.poi.xssf.usermodel.XSSFWorkbook;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    
    import com.google.common.collect.Lists;
    import com.google.common.collect.Maps;
    import com.szcatic.entity.ExcelFoot;
    import com.szcatic.entity.ExcelTitleHead;
    import com.szcatic.service.ExcelField;
    
    public class ExportExcelUtils3 {
    	
    	private static Logger logger = LoggerFactory.getLogger(ExportExcelUtils3.class);
    	
    	public static <T1, T2> void exportDateToExcel(Class<T1> clzz, List<T1> list, HttpServletResponse response, 
    			String fileName, T2 t2, ExcelTitleHead ... heads) {
    		ExcelFoot<T2> excelFoot = new ExcelFoot<T2>(new ExcelTitleHead("汇总:", null, null, 0, 0), t2);
    		exportDateToExcel(clzz, ExcelField.class, "sort", "title", list, response, fileName, excelFoot, heads);
    	}
    	
    	public static <T1, T2> void exportDateToExcel(Class<T1> clzz, List<T1> list, String fileName, 
    			T2 t2, ExcelTitleHead ... heads) {
    		ExcelFoot<T2> excelFoot = new ExcelFoot<T2>(new ExcelTitleHead("汇总:", null, null, 0, 0), t2);
    		exportDateToExcel(clzz, ExcelField.class, "sort", "title", list, fileName, excelFoot, heads);
    	}
    	
    	/**
    	 * 导出数据到Excel
    	 * @param clzz
    	 * @param annotationClass
    	 * @param sortName
    	 * @param titleName
    	 * @param list
    	 * @param response
    	 * @param fileName
    	 * @param heads
    	 */
    	private static <T extends Annotation, E, T2> void exportDateToExcel(Class<E> clzz, Class<T> annotationClass, 
    			String sortName, String titleName, List<E> list, String fileName, ExcelFoot<T2> excelFoot, 
    			ExcelTitleHead ... heads) {
    		FileOutputStream fos = null;
    		Workbook wb = null;
    		try {
    			fos = new FileOutputStream(new File(fileName));
    			wb = getWorkbook(clzz, annotationClass, sortName, titleName, list, fileName, excelFoot, heads);
    			// 进行输出,下载到本地
    	        wb.write(fos);
    	        fos.flush();
    			// 导出需要的数据到表格
    			logger.info("export excel success");
    		} catch (UnsupportedEncodingException e) {
    			e.printStackTrace();
    			logger.error("ExportExcelUtils3-》exportDateToExcel-》UnsupportedEncodingException");
    			logger.error(e.getMessage());
    		} catch (IOException e) {
    			e.printStackTrace();
    			logger.error("ExportExcelUtils3-》exportDateToExcel-》IOException");
    			logger.error(e.getMessage());
    		}finally {
    			if(fos != null) {
    				try {
    					fos.close();
    				} catch (IOException e) {
    					e.printStackTrace();
    					logger.error("ExportExcelUtils3-》exportDateToExcel-》finally-》IOException");
    					logger.error(e.getMessage());
    				}
    			}
    			if (wb != null) {
    				try {
    					wb.close();
    				} catch (IOException e) {
    					e.printStackTrace();
    				}
    			}
    		}
    	}
    	
    	/**
    	 * 导出数据到Excel
    	 * @param clzz
    	 * @param annotationClass
    	 * @param sortName
    	 * @param titleName
    	 * @param list
    	 * @param response
    	 * @param fileName
    	 * @param heads
    	 */
    	public static <T extends Annotation, E, T2> void exportDateToExcel(Class<E> clzz, Class<T> annotationClass, String sortName, 
    			String titleName, List<E> list, HttpServletResponse response, String fileName, ExcelFoot<T2> excelFoot, 
    			ExcelTitleHead ... heads) {
    		OutputStream os = null;
    		try {
            	// 设置导出的编码格式,此处统一为UTF-8
            	response.setContentType("application/vnd.ms-excel;charset=utf-8");
            	// 设置导出文件的名称
    			response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("utf-8"), "iso8859-1"));
    			os = response.getOutputStream();
    			Workbook wb = getWorkbook(clzz, annotationClass, sortName, titleName, list, fileName, excelFoot, heads);
    			// 进行输出,下载到本地
    	        wb.write(os);
    	        os.flush();
    			// 导出需要的数据到表格
    			logger.info("export excel success");
    		} catch (UnsupportedEncodingException e) {
    			e.printStackTrace();
    			logger.error("ExportExcelUtils3-》exportDateToExcel-》UnsupportedEncodingException");
    			logger.error(e.getMessage());
    		} catch (IOException e) {
    			e.printStackTrace();
    			logger.error("ExportExcelUtils3-》exportDateToExcel-》IOException");
    			logger.error(e.getMessage());
    		}finally {
    			if(os != null) {
    				try {
    					os.close();
    				} catch (IOException e) {
    					e.printStackTrace();
    					logger.error("ExportExcelUtils3-》exportDateToExcel-》finally-》IOException");
    					logger.error(e.getMessage());
    				}
    			}
    		}
    	}
    
    	private static <T extends Annotation, E, T2> Workbook getWorkbook(Class<E> clzz, Class<T> annotationClass, String sortName, 
    			String titleName, List<E> list, String fileName, ExcelFoot<T2> excelFoot, ExcelTitleHead ... heads) {
    		Workbook wb;
    		//创建工作表
    		if (isExcel2003(fileName)) {
    			wb = new HSSFWorkbook();
    		}else {
    			wb = new XSSFWorkbook();
    		}
    		
    		if ((list == null || list.isEmpty()) && (heads == null || heads.length == 0)) {
    			return wb;
    		}
    		// 创建sheet页
    		Sheet sheet = wb.createSheet();
    		sheet.autoSizeColumn(1, true);
            // 单元格样式
            CellStyle titleStyle = getTitleStyle(wb);
            CellStyle cellStyle = getCellStyle(wb);
            CellStyle footStyle = getFootStyle(wb);
    		Integer maxTitleRow = fillTitle(sheet, titleStyle, heads);
    		Integer maxTitleRow2 = fillDataToExcel(sheet, clzz, annotationClass, list, maxTitleRow, sortName, titleName, titleStyle, cellStyle, excelFoot);
    		fillFootData(sheet, annotationClass, sortName, maxTitleRow2, footStyle, excelFoot);
    		return wb;
    	}
    	
    	/**
    	 * 填充数据到Excel
    	 * @param <E>
    	 * @param <T>
    	 * @param clzz 
    	 * @param annotationClass 提供注解的类
    	 * @param list 数据列表
    	 * @param maxTitleRow 
    	 * @param sortName 排序的方法名
    	 * @param titleName 导出字段的标题方法名
    	 * @param titleName 标题头单元格样式
    	 * @param titleName 数据单元格样式
    	 */
    	private static <T extends Annotation, E, T2> Integer fillDataToExcel(Sheet sheet, Class<E> clzz, Class<T> annotationClass, 
    			List<E> list, Integer maxTitleRow, String sortName, String titleName, CellStyle titleStyle, CellStyle cellStyle,
    			ExcelFoot<T2> excelFoot) {
    		Map<String, T> map = getClassAnnotationMap(clzz, annotationClass);
    		List<Map.Entry<String, T>> sortList = mapSort(map, annotationClass, sortName);
    		List<String> headerList = getHeaderList(annotationClass, titleName, sortList);
    		Integer maxTitleRow2 = fileColumnTitle(headerList, titleStyle, sheet, maxTitleRow);
    		if (list == null || list.isEmpty()) {
    			return maxTitleRow2;
    		}
    		List<String> methodNames = getMethodNameList(sortList);
    		Integer maxDadaRow = fileColumnData(list, methodNames, cellStyle, sheet, maxTitleRow2);
    		return maxDadaRow;
    	}
    	
    	/**
    	 * 填充foot行数据
    	 * @param excelFoot
    	 */
    	private static <T1, T2 extends Annotation> void fillFootData(Sheet sheet, Class<T2> annotationClass, String sortName, 
    			Integer maxTitleRow, CellStyle footStyle, ExcelFoot<T1> excelFoot) {
    		if (excelFoot == null) {
    			return;
    		}
    		ExcelTitleHead head = excelFoot.getExcelTitleHead();
    		head.setStartRow(maxTitleRow + 1);
    		head.setLastRow(maxTitleRow + 1);
    		fillTitle(sheet, footStyle, head);
    		Cell cell;
    		Object obj;
    		Row row = sheet.getRow(head.getStartRow());
    		T1 t = excelFoot.getT();
    		Map<String, T2> map = getClassAnnotationMap(t.getClass(), annotationClass);
    		List<Map.Entry<String, T2>> sortList = mapSort(map, annotationClass, sortName);
    		List<String> methodNames = getMethodNameList(sortList);
    		for(int i = 0; i < methodNames.size(); i++) {
    			cell = row.createCell(head.getLastColmun() + (i + 1));
    			obj = getMethodReturnValue(t, methodNames.get(i));
    			cell.setCellValue(objectToString(obj));
    			cell.setCellStyle(footStyle);
    		}
    	}
    
    	/**
    	 * 填充主数据到Excel
    	 * @param list 主数据列表
    	 * @param methodNames
    	 * @param titleStyle
    	 * @param sheet
    	 * @param maxTitleRow
    	 * @return
    	 */
    	private static <T> Integer fileColumnData(List<T> list, List<String> methodNames, CellStyle cellStyle, Sheet sheet,
    			Integer maxDadaRow) {
    		Row row;
    		Cell cell;
    		Object obj;
    		T t;
    		for (int i = 0; i < list.size(); i++) {
    			row = sheet.createRow(++maxDadaRow);
    			t = list.get(i);
    			for(int j = 0; j < methodNames.size(); j++) {
    				cell = row.createCell(j);
    				obj = getMethodReturnValue(t, methodNames.get(j));
    				cell.setCellValue(objectToString(obj));
    				cell.setCellStyle(cellStyle);
    			}
    		}
    		return maxDadaRow;
    	}
    
    	/**
    	 * 获取方法名列表
    	 * @param sortList
    	 * @return List
    	 */
    	private static <T> List<String> getMethodNameList(List<Entry<String, T>> list) {
    		List<String> list2 = Lists.newArrayList();
    		for (Entry<String, T> entry : list) {
    			list2.add(entry.getKey());
    		}
    		return list2;
    	}
    
    	/**
    	 * 
    	 * @param list
    	 * @param cellStyle
    	 * @param sheet
    	 * @param maxTitleRow
    	 * @return
    	 */
    	private static Integer fileColumnTitle(List<String> list, CellStyle cellStyle, Sheet sheet, Integer maxTitleRow) {
    		Row row = sheet.createRow(++maxTitleRow);
    		Cell cell;
    		for (int i = 0; i < list.size(); i++) {
    			cell = row.createCell(i);
    			cell.setCellValue(list.get(i));
    			cell.setCellStyle(cellStyle);
    		}
    		return maxTitleRow;
    	}
    
    	/**
    	 * 获取列标题头列表
    	 * @param annotationClass
    	 * @param list2
    	 * @param titleName
    	 * @return List
    	 */
    	private static <T> List<String> getHeaderList(Class<T> annotationClass, String titleName, List<Map.Entry<String, T>> list) {
    		List<String> list2 = Lists.newArrayList();
    		for (Entry<String, T> entry : list) {
    			list2.add(String.valueOf(getReturnValue(annotationClass, titleName, entry.getValue())));
    		}
    		return list2;
    	}
    	
    	/**
    	 * 标题头单元格样式设置
    	 * @param wb
    	 * @return
    	 */
    	private static CellStyle getTitleStyle(Workbook wb) {
    		CellStyle titleStyle = wb.createCellStyle();
    		// 字体样式
            Font font = wb.createFont();
            // 粗体
            font.setBold(true);
            titleStyle.setFont(font);
            // 水平居中
            titleStyle.setAlignment(HorizontalAlignment.CENTER);
            // 垂直居中
            titleStyle.setVerticalAlignment(VerticalAlignment.CENTER);
    		return titleStyle;
    	}
    	
    	/**
    	 * 数据单元格样式设置
    	 * @param wb
    	 * @return
    	 */
    	private static CellStyle getCellStyle(Workbook wb) {
    		CellStyle cellStyle = wb.createCellStyle();
    		cellStyle.setAlignment(HorizontalAlignment.CENTER);
    		cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
    		return cellStyle;
    	}
    	
    	private static CellStyle getFootStyle(Workbook wb) {
    		CellStyle cellStyle = wb.createCellStyle();
    		cellStyle.setAlignment(HorizontalAlignment.CENTER);
    		cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
    		Font font = wb.createFont();
    		font.setColor(Font.COLOR_RED);
    		cellStyle.setFont(font);
    		return cellStyle;
    	}
    	
    	
    	/**
    	 * 填充标题头
    	 * @param sheet 
    	 * @param titleStyle
    	 * @param heads
    	 * @return Integer 标题头的最大行,如果为-1,表示没有标题行
    	 */
    	private static Integer fillTitle(Sheet sheet, CellStyle titleStyle, ExcelTitleHead... heads) {
    		Integer maxRow = -1;
    		if (heads == null || heads.length == 0) {
    			return maxRow;
    		}
    		Row row;
    		Cell cell;
    		CellRangeAddress region;
    		Integer lastRow;
    		for(int i = 0; i < heads.length; i++) {
    			//设置单元格范围:参数(int firstRow, int lastRow, int firstCol, int lastCol)
    			region = new CellRangeAddress(heads[i].getStartRow(), heads[i].getLastRow(), heads[i].getStartColmun(), heads[i].getLastColmun());
    			if (heads[i].getLastRow() + heads[i].getLastColmun() - heads[i].getStartRow() - heads[i].getStartColmun() > 0) {
    				//合并单元格
    				sheet.addMergedRegion(region);
    			}
    			//生成行
    			row = sheet.createRow(heads[i].getStartRow());
    		}
    		for(int i = 0; i < heads.length; i++) {
    			//获取生成的行
    			row = sheet.getRow(heads[i].getStartRow());
    			//生成列
    			cell = row.createCell(heads[i].getStartColmun());
    			cell.setCellValue(heads[i].getName());
    			cell.setCellStyle(titleStyle);
    			lastRow = heads[i].getLastRow();
    			if (maxRow < lastRow) {
    				maxRow = lastRow;
    			}
    		}
    		return maxRow;
    	}
    	
    	/**
    	 * 获取包含@T注解的方法以及注解的内容
    	 * @param clzz
    	 * @param annotationClass 注解接口类
    	 * @return Map:方法名为key,注解内容为value
    	 */
    	private static <T extends Annotation, E> Map<String, T> getClassAnnotationMap(Class<E> clzz, Class<T> annotationClass) {
    		Map<String, T> map = Maps.newHashMap();
    		Method[] methods = clzz.getDeclaredMethods();
    		if (methods == null || methods.length == 0) {
    			return map;
    		}
    		T annotation;
    		for (Method method : methods) {
    			if(method.isAnnotationPresent(annotationClass)) {
    				//得到注解
    				annotation = method.getAnnotation(annotationClass);
    				map.put(method.getName(), annotation);
    			}
    		}
    		return map;
    	}
    	
    	/**
    	 * 对Map集合进行排序
    	 * @param map 需要排序的Map集合
    	 * @param clzz class类
    	 * @param name 方法名
    	 * @return List
    	 */
    	private static <T> List<Map.Entry<String, T>> mapSort(Map<String, T> map, Class<T> clzz, String name) {
    		List<Map.Entry<String, T>> list = new ArrayList<Map.Entry<String, T>>(map.entrySet());
    		Collections.sort(list, new Comparator<Map.Entry<String, T>>() {
    			// 升序排序
    			public int compare(Entry<String, T> o1, Entry<String, T> o2) {
    				return (Integer) getReturnValue(clzz, name, o1.getValue()) 
    						- (Integer) getReturnValue(clzz, name, o2.getValue());
    			}
    		});
    		return list;
    	}
    	
    	/**
         * 获取方法的返回值
         * @param clzz 
         * @param name 方法名
         * @return
         */
        private static <T> Object getReturnValue(Class<T> clzz, String name, T t) {
        	Object value = null;
        	try {
        		Method method = clzz.getMethod(name);
        		value = method.invoke(t);
        		return value;
        	}catch (NoSuchMethodException e) {
        		e.printStackTrace();
        	}catch (SecurityException e) {
        		e.printStackTrace();
        	}catch (IllegalAccessException e) {
        		e.printStackTrace();
        	}catch (IllegalArgumentException e) {
        		e.printStackTrace();
        	}catch (InvocationTargetException e) {
        		e.printStackTrace();
        	}
        	return value;
        }
        
        /**
         * 获取方法的返回值
         * @param T 实体类 
         * @param methodName 方法名
         * @return Object
         */
    	private static <T> Object getMethodReturnValue(T t, String methodName) {
        	Object obj = null;
        	try {
    			obj = t.getClass().getMethod(methodName).invoke(t);
    		}catch (NoSuchMethodException e) {
    			e.printStackTrace();
    	    }catch (SecurityException e) {
    	    	e.printStackTrace();
    		} catch (IllegalAccessException e) {
    			e.printStackTrace();
    		} catch (IllegalArgumentException e) {
    			e.printStackTrace();
    		} catch (InvocationTargetException e) {
    			e.printStackTrace();
    		}
        	return obj;
        }
        
        private static String objectToString(Object obj) {
        	if (obj == null) {
    			return "";
    		}
        	String str;
        	try {
        		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        		if(obj instanceof Date) {
        			str = sdf.format(obj);
        		}else {
        			str = String.valueOf(obj);
        		}
    		} catch (Exception e) {
    			str = "";
    		}
        	return str;
        }
        
        /**
    	 * 判断是不是2003格式的Excel
    	 * @param filePath
    	 * @return boolean : true表示是2003格式的Excel,false表示不是
    	 */
    	private static boolean isExcel2003(String filePath) {
    		return filePath.matches("^.+\\.(?i)(xls)$");
    	}
    }
    
    

     

  5. 实体类 
    package com.szcatic.entity;
    
    import java.io.Serializable;
    
    /**
     * Excel标题头实体类
     * 
     * @author zsx
     * @version 2018-09-26
     *
     */
    public class ExcelTitleHead implements Serializable {
    
    	private static final long serialVersionUID = 1L;
    
    	private String name; // 标题名
    	private Integer startRow; // 起始行
    	private Integer lastRow; // 最后行
    	private Integer startColmun; // 起始列
    	private Integer lastColmun; // 最后列
    	
    	public ExcelTitleHead() {
    		super();
    	}
    	
    	/**
    	 * 
    	 * @param name 标题名
    	 * @param startRow 起始行
    	 * @param lastRow 最后行
    	 * @param startColmun 起始列
    	 * @param lastColmun 最后列
    	 */
    	public ExcelTitleHead(String name, Integer startRow, Integer lastRow, Integer startColmun, Integer lastColmun) {
    		super();
    		this.name = name;
    		this.startRow = startRow;
    		this.lastRow = lastRow;
    		this.startColmun = startColmun;
    		this.lastColmun = lastColmun;
    	}
    
    	public String getName() {
    		return name;
    	}
    
    	public void setName(String name) {
    		this.name = name;
    	}
    
    	public Integer getStartRow() {
    		return startRow;
    	}
    
    	public void setStartRow(Integer startRow) {
    		this.startRow = startRow;
    	}
    
    	public Integer getLastRow() {
    		return lastRow;
    	}
    
    	public void setLastRow(Integer lastRow) {
    		this.lastRow = lastRow;
    	}
    
    	public Integer getStartColmun() {
    		return startColmun;
    	}
    
    	public void setStartColmun(Integer startColmun) {
    		this.startColmun = startColmun;
    	}
    
    	public Integer getLastColmun() {
    		return lastColmun;
    	}
    
    	public void setLastColmun(Integer lastColmun) {
    		this.lastColmun = lastColmun;
    	}
    
    	@Override
    	public String toString() {
    		return "ExcelTitleHead [name=" + name + ", startRow=" + startRow + ", lastRow=" + lastRow + ", startColmun="
    				+ startColmun + ", lastColmun=" + lastColmun + "]";
    	}
    	
    	
    }
    
    
    package com.szcatic.entity;
    
    import com.szcatic.entity.ExcelTitleHead;
    
    /**
     * ExcelFoot实体类
     * 
     * @author zsx
     * @version 2018-09-26
     *
     */
    public class ExcelFoot<T> {
    
    	private ExcelTitleHead excelTitleHead;
    	private T t;
    
    	public ExcelFoot() {
    		super();
    	}
    	
    	public ExcelFoot(ExcelTitleHead excelTitleHead, T t) {
    		super();
    		this.excelTitleHead = excelTitleHead;
    		this.t = t;
    	}
    
    	public ExcelTitleHead getExcelTitleHead() {
    		return excelTitleHead;
    	}
    
    	public void setExcelTitleHead(ExcelTitleHead excelTitleHead) {
    		this.excelTitleHead = excelTitleHead;
    	}
    
    	public T getT() {
    		return t;
    	}
    
    	public void setT(T t) {
    		this.t = t;
    	}
    
    	@Override
    	public String toString() {
    		return "ExcelFoot [excelTitleHead=" + excelTitleHead + ", t=" + t + "]";
    	}
    
    }
    
    
    package com.szcatic.entity;
    
    import java.io.Serializable;
    import java.util.List;
    
    import com.szcatic.service.ExcelField;
    
    /**
     * 人实体类
     * @author zsx
     * @version 2018-09-26
     */
    public class Person implements Serializable {
    
    	private static final long serialVersionUID = 1L;
    	
    	private Long id;
    	private String name;
    	private Integer age;
    	private List<String> hobby;
    	
    	public void setId(Long id) {
    		this.id = id;
    	}
    	
    	@ExcelField(title="id", sort=10)
    	public Long getId() {
    		return this.id;
    	}
    
    	public void setName(String name) {
    		this.name = name;
    	}
    	
    	@ExcelField(title="姓名", sort=30)
    	public String getName() {
    		return this.name;
    	}
    
    	public void setAge(Integer age) {
    		this.age = age;
    	}
    	
    	@ExcelField(title="年龄", sort=20)
    	public Integer getAge() {
    		return this.age;
    	}
    
    	public void setHobby(List<String> hobby) {
    		this.hobby = hobby;
    	}
    
    	public List<String> getHobby() {
    		return this.hobby;
    	}
    
    	@Override
    	public String toString() {
    		return "Person [id=" + id + ", name=" + name + ", age=" + age + ", hobby=" + hobby + "]";
    	}
    	
    }
    
    
    package com.szcatic.entity;
    
    import java.io.Serializable;
    import com.szcatic.service.ExcelField;
    
    /**
     * 用户实体类
     * @author zsx
     * @version 2018-09-26
     */
    public class User implements Serializable {
    
    	private static final long serialVersionUID = 1L;
    	
    	private String userName; // 用户名
    	private String password; // 密码
    	private Integer age; // 年龄
    	private String gender; // 性别
    	private String email; // 邮箱
    	
    	@ExcelField(title="用户名", sort=10)
    	public String getUserName() {
    		return userName;
    	}
    
    	public void setUserName(String userName) {
    		this.userName = userName;
    	}
    	
    	@ExcelField(title="密码", sort=30)
    	public String getPassword() {
    		return password;
    	}
    
    	public void setPassword(String password) {
    		this.password = password;
    	}
    	
    	@ExcelField(title="年龄", sort=20)
    	public Integer getAge() {
    		return age;
    	}
    
    	public void setAge(Integer age) {
    		this.age = age;
    	}
    	
    	@ExcelField(title="性别", sort=50)
    	public String getGender() {
    		return gender;
    	}
    	
    	public void setGender(String gender) {
    		this.gender = gender;
    	}
    
    	@ExcelField(title="邮箱", sort=40)
    	public String getEmail() {
    		return email;
    	}
    	
    	public void setEmail(String email) {
    		this.email = email;
    	}
    
    	@Override
    	public String toString() {
    		return "User [userName=" + userName + ", password=" + password + ", age=" + age + ", gender=" + gender
    				+ ", email=" + email + "]";
    	}
    
    
    }
    
    

     

  6. 测试类
    package com.szcatic.test;
    
    import java.util.ArrayList;
    import java.util.List;
    
    import org.junit.jupiter.api.Test;
    
    import com.szcatic.entity.ExcelTitleHead;
    import com.szcatic.entity.Person;
    import com.szcatic.entity.User;
    import com.szcatic.util.ExportExcelUtils3;
    
    /**
     * 导出工具类测试类
     * @author zsx
     * @version 2018-09-26
     *
     */
    public class ExportExcelUtils3Test {
    	@Test
    	void testExportDateToExcel() {
    		ExcelTitleHead head = new ExcelTitleHead("主标题", 0, 1, 0, 4);
    		ExcelTitleHead head0 = new ExcelTitleHead("主标题1", 0, 1, 5, 6);
    		ExcelTitleHead head1 = new ExcelTitleHead("副标题1", 2, 3, 0, 0);
    		ExcelTitleHead head2 = new ExcelTitleHead("副标题2", 2, 3, 1, 1);
    		
    		ExcelTitleHead head3 = new ExcelTitleHead("副标题3", 2, 3, 2, 4);
    		List<User> list = new ArrayList<>();
    		User user = new User();
    		user.setUserName("zhangsan");
    		user.setAge(20);
    		user.setGender("男");
    		user.setEmail("zhangsan@163.com");
    		user.setPassword("1234");
    		list.add(user);
    		User user2 = new User();
    		user2.setUserName("lisi");
    		user2.setAge(25);
    		user2.setGender("男");
    		user2.setEmail("lisi@163.com");
    		user2.setPassword("1234");
    		list.add(user2);
    		Person person = new Person();
    		person.setId(2L);
    		person.setAge(10);
    		person.setName("zhaoyun");
    		String fileName = "F:/newProject/export.xls";
    		String fileName1 = "F:/newProject/export.xlsx";
    		ExportExcelUtils3.exportDateToExcel(User.class, list, fileName, person, head, head0, head1, head2, head3);
    		ExportExcelUtils3.exportDateToExcel(User.class, list, fileName1, person, head, head0, head1, head2, head3);
    		System.out.println("生成文件成功");
    	}
    }
    

     

  7. 运行结果

    [23:23:55:177] [INFO] - com.szcatic.util.ExportExcelUtils3.exportDateToExcel(ExportExcelUtils3.java:81) - export excel success
    [23:23:56:258] [INFO] - com.szcatic.util.ExportExcelUtils3.exportDateToExcel(ExportExcelUtils3.java:81) - export excel success
    生成文件成功

 

java实现excel的导出功能(超简单实现方式) java实现excel的导出功能(超简单实现方式) 1、自定义接口注解 @Documented @Target(value = {ElementType.METHOD, ElementType.TYPE}) @Retention(value = RetentionPolicy.RUNTIME) public @interface AsyncExcelService { /** * 标识code * @return */ String taskCode(); 阅读详情

相关推荐

若依框架中Excel导出模板功能

RuoYi框架中Excel导入导出功能

qq_37388841的博客 2802

java自定义注解实现导出excel功能

项目开发时会经常遇到需要把数据导出成excel文档的需求,为提示开发效率,实现了通过在entity上加注解即可使用导出功能。3.业务导出使用时,需设置export方法参数。2.增加工具类辅助注解导出实现。1. 自定义导出注解。

qwertyu1234567g的博客 1408

Excel文档和JavaBean转换工具——excel导入导出

excel_io.jar 工具是依赖于poi和poi-ooxml两个apached的jar包 进行的开发的,分别依赖3.14 和3.17两个版本,请下载的用户注意如果名字为excel_io-poi3.14.jar na依赖的就是poi 的3.14版本了。如果名为 excel_io-poi3.17.jar,那么就是依赖的 poi 的3.17版本了。 具体使用介绍请转博文https://mp.csdn.net/postedit/83686999

Java之基于注解的Excel导出

数据库Excel导出操作代码过于冗长惨不忍睹,无法复用。 目录 第一步:自定义注解: 第二步:实体类: 第三步:解析工具类: 第四步:使用: 依赖: <dependency> <groupId>cn.afterturn</groupId> <artifactId>easypoi-base</artifactId> <version>4.1.2</ver

m0_67402774的博客 1144

基于C#的软PLC梯形图编辑器开发实战

本文详细介绍了基于C#开发软PLC梯形图编辑器的实战过程。文章从核心数据结构设计入手,阐述了如何利用C#的面向对象特性构建梯形图元素模型,并实现了图形编辑、指令表输入、逻辑连接拓扑重建等关键功能。重点剖析了模拟PLC执行引擎的扫描周期与能流传递算法,让梯形图逻辑在PC上“活”起来。最后探讨了定时器指令实现、性能优化及项目集成等进阶内容,为工业自动化软件集成提供了灵活高效的解决方案。

weixin_28314575的博客 407

理解ADC:为什么需要抗混叠滤波器?

本文介绍 ADC 的混叠现象,引出抗混叠滤波器,并介绍一种开关电容滤波器,它具有很小的增益过渡带。

疯狂的运放 5968

通过注解方式导入导出execl

通过maven引入jar <properties> <java.version>1.8</java.version> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler....

550

Aircrack-ng实战指南:从基础扫描到高级密码破解

本文提供了一份详尽的Aircrack-ng实战指南,涵盖从环境搭建到密码破解的全过程。内容包括如何准备兼容的无线网卡与Kali Linux系统,使用airodump-ng进行网络扫描与信息收集,捕获WPA2握手包的关键步骤,以及利用字典文件进行密码破解的核心原理与技巧。文章强调该技术应仅用于授权的安全测试与学习,旨在帮助读者理解无线网络安全以加强自身防护。

m3n5b7v8c9x的博客 558

Java导出自定义Excel表格,一套组合拳解决

很多框架中都能直接支持自动生成关于单表的增删改查操作的前后端代码,但是复杂的多表操作就无法做到,因为复杂的业务操作跟着需求走,自定义Excel表格导出也是如此。中间涉及到的包都是Alibaba中的依赖包,能自动导入,大家可以多点进去看看里面内部的实现机制。🍪标记好需要合并的字段信息后,核心的合并策略参考以下代码,这里不做过多的阐述。

Fish_Vast的博客 3341

5.FxBlue跟单常见问题

fxblue喊单ea和fxblue跟单会在mt4/mt5客户端ea栏目里记录fxblue在跟单复制订单过程中的全面记录。在遇到问题时,我们首先要恢复默认参数尝试,然后再到ea栏找报错提示。 ​ 需要注意的是,是EA选项卡,而不是日志选项卡。 此外,您可以在 MT4/5 软件终端面板的"EA"选项卡中查看跟单记录,您可以通过右键单击 Experts 日志并从 MT4/5 的弹出菜单中选择“打开”来打开每日日志文件以及历史文件。 5.1 No “heartbeat” received 没有收到“心跳” 接收方

weixin_44406393的博客 1885

Lama:基于傅立叶卷积的分辨率鲁棒性大掩模修复

为了缓解修复网络和损失函数都缺乏有效的感受野这个问题,提出了大掩模修复(LaMa)。LaMa基于一种新的修复网络架构,该架构使用快速傅立叶卷积(FFC),具有图像范围的感受野;高感受野感知损失;大型训练掩码,释放前两个组件的潜力。

qq_44926214的博客 1422

POI导出Excel、JAVA根据POI封装Excel的导出(支持动态表头)

根据POI封装Excel的导出()说明代码 说明 之前不知道有easy-poi这个封装好的包。在使用poi的过程中,慢慢的根据实际业务封装的。 通过注解方式,生成Excel,支持动态表头。 代码 代码从接口调用开始说明 poi版本 ...

lq6812574的博客 3185

《Autosar从入门到精通-实战篇》总目录_培训教程持续更新中...

欢迎大家订阅《Autosar从入门到精通-实战篇》,下方整理了相关博文的目录(单击蓝色字体即可跳转),方便大家获取。 本专栏旨在:扫除Autosar工具链配置过程中的障碍,加深对Autosar理论的理解。 温馨提醒: 如有疑问,可在博文的“评论区”给小编留言,进行技术交流(评论区开启了验证功能,审核通过后,会显示); 如有疑问,也可以通过博文中的第一个图片联系小编,获取专栏/博文的实时状态; 由于工作限制,仅做个人技术交流。添加好友时,请备注您的“姓名-公司-职务...

「汽车电子助手」的博客 12万+

SpringBoot + hutool工具 实现动态表头导出Excel

动态表头定位:前端导出Excel时,选择需要导出的字段。 实现思路:使用 自定义注解 ,映射 实体类字段和表头名称,再通过反射获取到实体类的自定义注解,对比 前端带过来的 表头集合,通过 hutool导出功能实现。 导入 相关依赖 <!-- hutool 工具依赖 --> <dependency> <groupId>cn.hutool</groupId> <

qq_44136551的博客 1万+

PyQt5开发编译器安装(PyCharm安装)

PyCharm 提供了最完整的 PyQt5 开发体验,特别是其集成的调试工具和 Qt Designer 支持,能显著提高开发效率。是最受欢迎和功能最完整的 IDE。它专门为 Python 开发优化,对 PyQt5 有很好的支持。右键运行该文件,如果出现窗口说明配置成功。对于 PyQt5 开发,

啊渊的专栏 431

Android功耗系列专题理论之十一:高通QCOM平台待机功耗问题分析方法

本文详细介绍了高通QCOM平台待机功耗问题的分析方法。首先强调测试环境标准化的重要性,包括关闭无线功能、日志记录和非必要传感器。重点分析了硬件连接检查、驱动配置验证、电源管理策略优化等关键步骤。文章详细讲解了射频校准、时钟源/中断分析、子系统状态检查等专业技术方法,并提供了具体的命令行操作示例。此外还介绍了外设拆解、外灌电压测试等硬件排查手段,以及功耗分解板、波形分析等高级诊断技术。最后强调了固件版本验证和环境因素测试的必要性,为工程师提供了系统性的功耗问题排查思路。

781

 Excel导出以注解方式实现

注解类 import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Excel注解定义 */ @Target({ElementType.METHOD, ElementType.FIELD, ElementType.TYPE})

qq_33550151的博客 1018

文档:亲测可用解决vnc灰屏,黑屏,鼠标大黑叉情况

主要解决vnc-viewer灰屏,黑屏,鼠标大黑叉等现象,详细见文档。

优雅的实现 Excel 导入导出

日常在做后台系统的时候会很频繁的遇到Excel导入导出的问题,正好这次在做一个后台系统,就想着写一个公用工具来进行Excel的导入导出。一般我们在导出的时候都是导出的前端表格,而前端表格同...

weixin_45727359的博客 278

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

全球国家地区城市数据

MySQL全球国家地区城市数据报。。。。。。。。。。。。

链接数据库生成java bean_FoxJava根据数据库表自动生成JavaBean+MyBatis注解+导出Excel...

/***********************原创基本描述**********************************/0、javaBean后缀可以自定义1、工具本身是非常简单的,每个人都能做就是使用模板替换生成相应文件2、工具主要针对SpringMvc+Mybatis注解+Mysql生成对象,dao、sqlDao、interface、实现接口3、根据表生成Excel4、生成成功后倒入到...

weixin_33016355的博客 179

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

JAVA POI导出带动态下拉框EXCEL模板

先看看效果,前4个均是从数据库查询出来的下拉选择: 步骤一:写EXCEL 注解: import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target( { java.lang.annotation.ElementType.FIELD }

chengmin123456789的博客 4639

java导出excel 序号_java指定顺序通过映射导出excel

packagecom.ihrm.common.poi.utils;importcom.ihrm.domain.poi.ExcelAttribute;importlombok.Getter;importlombok.Setter;import org.apache.poi.hssf.usermodel.*;importorg.apache.poi.poifs.filesystem.POIFSFile...

weixin_27021789的博客 885

java导出Excel文件

【代码】java导出Excel文件。

atokinesis的博客 1655

注解+反射优雅的实现Excel导入导出(通用版),飘了!

来源:blog.csdn.net/youzi1394046585/article/details/86670203日常在做后台系统的时候会很频繁的遇到Excel导入导出的问题,正好这次在做...

java思维导图 137

java excel导出

java excel导出 maven <!--读取excel--> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>4.0.1</version> </dependency>

qq_25064691的博客 543
上一篇: freemarker简单案例
下一篇: 导入Excel时,根据注解生成实体类
禅剑一如
博客等级 码龄10年 24粉丝 178原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值