栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java集成easyApi实现excel数据导入

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java集成easyApi实现excel数据导入

pom.xml

       
            com.alibaba
            easyexcel
            2.1.4
        

controller方法:

public JSonObject readExcelCenter(MultipartFile file) throws Exception {
        JSonObject jsonObject = new JSonObject();
        int success = 0;
        int error = 0;
        List list = ExcelUtil.readDCenterDemandEntityExcel(file);
        for(DCenterDemandEntity dCenterDemandEntity : list){
           boolean bool = dCenterDemandService.saveimport(dCenterDemandEntity);
           if(bool){
               success += 1;
           }else{
               error += 1;
           }
        }
        jsonObject.put("successNum",success);
        jsonObject.put("error",error);
        jsonObject.put("success",true);
        return jsonObject;
    }

实体:

import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.metadata.baseRowModel;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.ToString;

import java.io.Serializable;
import java.util.Date;


@Data
@ToString
public class DCenterDemandEntity extends baseRowModel implements Serializable {

    private static final long serialVersionUID = 1L;


    
    @ExcelProperty(index = 0)
    @ApiModelProperty(value = "城市")
    private String cityName;

    
    @ExcelProperty(index = 1)
    @ApiModelProperty(value = "需求")
    private String content;

    
    @ExcelProperty(index = 2)
    private String field;
}

ExcelUtil工具类:

package com.pro.main.utils;

import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.metadata.baseRowModel;
import com.alibaba.excel.metadata.Sheet;
import com.pro.main.fill.entity.DCenterDemand;
import com.pro.main.fill.entity.excelEntity.DCenterDemandEntity;
import com.pro.main.fill.entity.excelEntity.DProjectDemandEntity;
import com.pro.main.fill.entity.excelEntity.DProjectGroundEntity;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.List;


public class ExcelUtil {
    
    private ExcelUtil() {
    }

    private static List readExcel(String path, Class clazz) throws Exception {
        if (StringUtils.isNotEmpty(path)) {
            File file = new File(path);
            if (!file.exists()) {
                throw new Exception("文件不存在 !");
            }
            InputStream inputStream = new FileInputStream(file);
            BufferedInputStream bis = new BufferedInputStream(inputStream);
            return readExcel(bis, clazz);
        }
        return null;
    }

    private static List readExcel(File file, Class clazz) throws Exception {
        if (file != null && file.exists()) {
            InputStream inputStream = new FileInputStream(file);
            BufferedInputStream bis = new BufferedInputStream(inputStream);
            return readExcel(bis, clazz);
        }
        return null;
    }

    private static List readExcel(InputStream inputStream, Class clazz) throws Exception {
        return readExcel(inputStream, null, clazz);
    }

    private static List readExcel(MultipartFile excelFile, Class clazz) throws Exception {
        if (excelFile != null) {
            return readExcel(excelFile.getInputStream(), null, clazz);
        }
        return null;
    }

    public static List readExcel(InputStream inputStream, Object customContent, Class clazz) throws Exception {
        ExcelListener excelListener = new ExcelListener();
        ExcelReader excelReader;
        if (inputStream instanceof BufferedInputStream) {
            excelReader = new ExcelReader(inputStream, customContent, excelListener);
        } else {
            excelReader = new ExcelReader(new BufferedInputStream(inputStream), customContent, excelListener);
        }
        excelReader.read(new Sheet(1, 1, clazz));
        return excelListener.getDataList();
    }


    public static List readDCenterDemandEntityExcel(MultipartFile file) throws Exception{
        List list = readExcel(file,DCenterDemandEntity.class);
        return BeanCopy.convert(list, DCenterDemandEntity.class) ;
    }
    public static List readDProjectDemandEntityExcel(MultipartFile file) throws Exception{
        List list = readExcel(file,DProjectDemandEntity.class);
        return BeanCopy.convert(list, DProjectDemandEntity.class) ;
    }
    public static List readDProjectGroundEntityExcel(MultipartFile file) throws Exception{
        List list = readExcel(file,DProjectGroundEntity.class);
        return BeanCopy.convert(list, DProjectGroundEntity.class) ;
    }
}

ExcelListener:

package com.pro.main.utils;

import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

public class ExcelListener extends AnalysisEventListener {

    private List dataList = new ArrayList<>();

    
    @Override
    public void invoke(Object object, AnalysisContext context) {
        if (!checkObjAllFieldsIsNull(object)) {
            dataList.add(object);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {

    }

    private static final String SERIAL_VERSION_UID = "serialVersionUID";

    
    private static boolean checkObjAllFieldsIsNull(Object object) {
        if (null == object) {
            return true;
        }
        try {
            for (Field f : object.getClass().getDeclaredFields()) {
                f.setAccessible(true);
                //只校验带ExcelProperty注解的属性
                ExcelProperty property = f.getAnnotation(ExcelProperty.class);
                if (property == null || SERIAL_VERSION_UID.equals(f.getName())) {
                    continue;
                }
                if (f.get(object) != null && MyStringUtils.isNotBlank(f.get(object).toString())) {
                    return false;
                }
            }
        } catch (Exception e) {
            //do something
        }
        return true;
    }

    public List getDataList() {
        return dataList;
    }
}
 

BeanCopy:

package com.pro.main.utils;

import org.springframework.beans.*;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.support.DefaultConversionService;
import org.springframework.core.convert.support.GenericConversionService;
import org.springframework.util.Assert;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

public class BeanCopy {

	private final class DateToStringConverter implements Converter {
        private DateFormat df ;
		private DateToStringConverter(String format) {
            df = new SimpleDateFormat(format);
		}
		@Override
		public String convert(Date source) {

			return df.format(source);
		}
	}

	private static final String DATE_FORMAT = "yyyy-MM-dd";

	private static Object convertForProperty(Wrapper wrapper, Object object, Object value, String propertyName)
			throws TypeMismatchException {
		Object result;
		if (wrapper == null) {
			result = null;
		} else {
			wrapper.setWrappedInstance(object);
			result = wrapper.getBeanWrapper().convertForProperty(value, propertyName);
		}
		return result;
	}

	private static Object copyProperties(Object source, Object target) throws BeansException {
		Wrapper wrapper = new BeanCopy().new Wrapper(source);
		copyProperties(wrapper, source, target);
		return target;
	}

	
	private static void copyProperties(Wrapper wrapper, Object source, Object target) throws BeansException {
		Assert.notNull(source, "Source must not be null");
		Assert.notNull(target, "Target must not be null");

		Class actualEditable = target.getClass();
		PropertyDescriptor[] targetPds = BeanUtils.getPropertyDescriptors(actualEditable);

		for (PropertyDescriptor targetPd : targetPds) {
			if (targetPd.getWriteMethod() != null) {
				PropertyDescriptor sourcePd = BeanUtils.getPropertyDescriptor(source.getClass(), targetPd.getName());
				if ( sourcePd.getReadMethod() != null) {
					try {
						Method readMethod = sourcePd.getReadMethod();
						if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
							readMethod.setAccessible(true);
						}
						Object value = readMethod.invoke(source);
						// 判断是否类型不一致
						if (value != null && !(targetPd.getPropertyType().isInstance(value))) {
							// 数据转型
							value = convertForProperty(wrapper, target, value, targetPd.getName());
						}
						Method writeMethod = targetPd.getWriteMethod();
						if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
							writeMethod.setAccessible(true);
						}
						writeMethod.invoke(target, value);
					} catch (Exception ex) {
						throw new FatalBeanException("Could not copy properties from source to target", ex);
					}
				}
			}
		}

	}

	private final class Wrapper {

		private GenericConversionService conversion;
		private BeanWrapperImpl bean;

		private Wrapper(Object object) {
			conversion = initDefaultConversionService();
			bean = initDefaultBeanWrapper(conversion, object);
		}

		private void setWrappedInstance(Object object) {
			bean.setWrappedInstance(object);
		}

		private GenericConversionService initDefaultConversionService() {
			GenericConversionService conversionService = new DefaultConversionService();
			conversionService.addConverter(new DateToStringConverter(DATE_FORMAT));
			return conversionService;
		}

		private BeanWrapperImpl initDefaultBeanWrapper(@SuppressWarnings("hiding") ConversionService conversion,
                                                       Object object) {
			BeanWrapperImpl beanWrapper = new BeanWrapperImpl(object);
			beanWrapper.setConversionService(conversion);
			SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
			dateFormat.setLenient(false);
			beanWrapper.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
			return beanWrapper;
		}

		private BeanWrapperImpl getBeanWrapper() {
			return bean;
		}
	}

	
	private static void convert(Object source, Object target) {
		copyProperties(source, target);
	}

	public static  List convert(List sources, Class targetClass) {
		List sourcesObj = sources;
		if (sourcesObj == null) {
			sourcesObj = Collections.emptyList();
		}
		List targets = new ArrayList<>(sourcesObj.size());
		BeanCopy.convert(sourcesObj, targets, targetClass);
		return targets;
	}

	private static  void convert(List sources, List targets, Class targetClass) {
		if (targets == null) {
			return;
		}
		targets.clear();
		if (sources == null) {
			return;
		}
		for (Object obj : sources) {
			try {
				T target = targetClass.newInstance();
				targets.add(target);
				convert(obj, target);
			} catch (Exception e) {
                //do something
				return;
			}
		}
	}
}

MyStringUtils:

package com.pro.main.utils;

public class MyStringUtils {

    private MyStringUtils() {}

    
    private static boolean isBlank(final CharSequence cs) {
        int strLen;
        if (cs == null || (strLen = cs.length()) == 0) {
            return true;
        }
        for (int i = 0; i < strLen; i++) {
            if (!Character.isWhitespace(cs.charAt(i))) {
                return false;
            }
        }
        return true;
    }

    public static boolean isNotBlank(final CharSequence cs) {
        return !isBlank(cs);
    }
}

转载请注明:文章转载自 www.mshxw.com
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号