poi-Excel导出工具类

本文介绍如何利用Java的poi库创建和导出Excel文件,详细讲解了 poi 的基本用法和关键步骤,包括设置工作簿、创建表格、填充数据等操作。
摘要由CSDN通过智能技术生成

/**
 * 导出Excel文件(导出“XLSX”格式,支持大数据量导出   @see org.apache.poi.ss.SpreadsheetVersion)

 */
public class ExportExcel {
   
	

			
	/**
	 * 工作薄对象
	 */
	private SXSSFWorkbook wb;
	
	/**
	 * 工作表对象
	 */
	private Sheet sheet;
	
	/**
	 * 样式列表
	 */
	private Map<String, CellStyle> styles;
	
	/**
	 * 当前行号
	 */
	private int rownum;
	
	/**
	 * 注解列表(Object[]{ ExcelField, Field/Method })
	 */
	List<Object[]> annotationList = Lists.newArrayList();
	
	/**
	 * 构造函数
	 * @param title 表格标题,传“空值”,表示无标题
	 * @param cls 实体对象,通过annotation.ExportField获取标题
	 */
	public ExportExcel(String title, Class<?> cls){
   
		this(title, cls, 1);
	}
	
	/**
	 * 构造函数
	 * @param title 表格标题,传“空值”,表示无标题
	 * @param cls 实体对象,通过annotation.ExportField获取标题
	 * @param type 导出类型(1:导出数据;2:导出模板)
	 * @param groups 导入分组
	 */
	public ExportExcel(String title, Class<?> cls, int type, int... groups){
   
		// Get annotation field 
		Field[] fs = cls.getDeclaredFields();
		for (Field f : fs){
   
			ExcelField ef = f.getAnnotation(ExcelField.class);
			if (ef != null && (ef.type()==0 || ef.type()==type)){
   
				if (groups!=null && groups.length>0){
   
					boolean inGroup = false;
					for (int g : groups){
   
						if (inGroup){
   
							break;
						}
						for (int efg : ef.groups()){
   
							if (g == efg){
   
								inGroup = true;
								annotationList.add(new Object[]{
   ef, f});
								break;
							}
						}
					}
				}else{
   
					annotationList.add(new Object[]{
   ef, f});
				}
			}
		}
		// Get annotation method
		Method[] ms = cls.getDeclaredMethods();
		for (Method m : ms){
   
			ExcelField ef = m.getAnnotation(ExcelField.class);
			if (ef != null && (ef.type()==0 || ef.type()==type)){
   
				if (groups!=null && groups.length>0){
   
					boolean inGroup = false;
					for (int g : groups){
   
						if (inGroup){
   
							break;
						}
						for (int efg : ef.groups()){
   
							if (g == efg){
   
								inGroup = true;
								annotationList.add(new Object[]{
   ef, m});
								break;
							}
						}
					}
				}else{
   
					annotationList.add(new Object[]{
   ef, m});
				}
			}
		}
		// Field sorting
		Collections.sort(annotationList, new Comparator<Object[]>() {
   
			@Override
            public int compare(Object[] o1, Object[] o2) {
   
				return new Integer(((ExcelField)o1[0]).sort()).compareTo(
						new Integer(((ExcelField)o2[0]).sort()));
			};
		});
		// Initialize
		List<String> headerList = Lists.newArrayList();
		for (Object[
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值