使用EasyPoi进行导入导出Excel(含多sheet导入导出操作)

本文算是对上篇 使用EasyPoi根据模板导出Excel或word文档  的补充吧

主要是直接进行导入导出,下面给出一个补充的工具类吧

/**
 * Excle 文件导入导出Util(easypoi)
 * @ClassName:EasyPoiUtil
 * @author leon
 * @createDate 2018年11月29日 下午15:25:27
 * @version v1.0
 * @classRemarks TODO
 */
public class EasyPoiUtil {
    private final static Logger logger = LoggerFactory.getLogger(EasyPoiUtil.class);
   /**
    * 功能描述:复杂导出Excel,包括文件名以及表名。创建表头
    *
    * @param list 导出的实体类
    * @param title 表头名称
    * @param sheetName sheet表名
    * @param pojoClass 映射的实体类
    * @param isCreateHeader 是否创建表头
    * @param fileName
    * @param response
    * @return 
   */
    public static void exportExcel(List list, String title, String sheetName, Class pojoClass, String fileName, boolean isCreateHeader, HttpServletResponse response) {
        ExportParams exportParams = new ExportParams(title, sheetName);
        exportParams.setCreateHeadRows(isCreateHeader);
        defaultExport(list, pojoClass, fileName, response, exportParams);
    }
 
 
    /**
     * 功能描述:复杂导出Excel,包括文件名以及表名,不创建表头
     *
     * @param list 导出的实体类
     * @param title 表头名称
     * @param sheetName sheet表名
     * @param pojoClass 映射的实体类
     * @param fileName
     * @param response
     * @return
     */
    public static void exportExcel(List list, String title, String sheetName, Class pojoClass, String fileName, HttpServletResponse response) {
        defaultExport(list, pojoClass, fileName, response, new ExportParams(title, sheetName));
    }
 
    /**
     * 功能描述:Map 集合导出
     * @param list 实体集合
     * @param fileName 导出的文件名称
     * @param response
     * @return
    */
    public static void exportExcel(List> list, String fileName, HttpServletResponse response) {
        defaultExport(list, fileName, response);
    }
 
    /**
     * 功能描述:默认导出方法
     * @param list 导出的实体集合
     * @param fileName 导出的文件名
     * @param pojoClass pojo实体
     * @param exportParams ExportParams封装实体
     * @param response
     * @return
     */
    private static void defaultExport(List list, Class pojoClass, String fileName, HttpServletResponse response, ExportParams exportParams) {
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list);
        if (workbook != null) {
            downLoadExcel(fileName, response, workbook);
        }
    }
 
    /**
     * 功能描述:Excel导出
     * @param fileName 文件名称
     * @param response
     * @param workbook Excel对象
     * @return
    */
    private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) {
        try {
            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-Type", "application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            throw new  RuntimeException(e);
        }
    }
 
    /**
     * 功能描述:默认导出方法
     * @param list 导出的实体集合
     * @param fileName 导出的文件名
     * @param response
     * @return
    */
    private static void defaultExport(List> list, String fileName, HttpServletResponse response) {
        Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF);
        if (workbook != null) ;
        downLoadExcel(fileName, response, workbook);
    }
    
    
    /**
     * 功能描述:根据文件路径来导入Excel
     * @param filePath 文件路径
     * @param titleRows 表标题的行数
     * @param headerRows 表头行数
     * @param pojoClass Excel实体类
     * @return
    */
    public static  List importExcel(String filePath, Integer titleRows, Integer headerRows, Class pojoClass) {
        //判断文件是否存在
        if (StringUtils.isBlank(filePath)) {
            return null;
        }
        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);
        params.setHeadRows(headerRows);
        List list = null;
        try {
            list = ExcelImportUtil.importExcel(new File(filePath), pojoClass, params);
        } catch (NoSuchElementException e) {
            throw new RuntimeException("模板不能为空");
        } catch (Exception e) {
            logger.error("系统错误:",e);
 
        }
        return list;
    }
 
    /**
     * 功能描述:根据接收的Excel文件来导入Excel,并封装成实体类
     * @param file 上传的文件
     * @param titleRows 表标题的行数
     * @param headerRows 表头行数
     * @param pojoClass Excel实体类
     * @return
     */
    public static  List importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class pojoClass) {
        if (file == null) {
            return null;
        }
        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);
        params.setHeadRows(headerRows);
        List list = null;
        try {
            list = ExcelImportUtil.importExcel(file.getInputStream(), pojoClass, params);
        } catch (NoSuchElementException e) {
            throw new RuntimeException("excel文件不能为空");
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
 
        }
        return list;
    }
 
 
}

 随便拿同事一个调用的实例看下吧,因为我这块主要负责是提供这些工具类和模板导出供项目开发使用,让同事避免踩坑,简单说就是我一人踩坑全项目组受用,就避免大家过多的花费时间在做一块上

使用EasyPoi进行导入导出Excel(含多sheet导入导出操作)_第1张图片

 

   给个测试例子吧,局部业务自行调整

@RestController
@RequestMapping("/import/poExcel")
@Api(value="多sheet数据导入及导出",tags="多sheet数据导入及导出")
public class PoExcelController {
	
	@Autowired
	private PoExcelService poExcelService;
	
	@RequestMapping(value = "/excelImport", method = RequestMethod.POST)  
    public JsonResult excelImport(MultipartFile file) throws IOException {  
        //根据file得到Workbook,主要是要根据这个对象获取,传过来的excel有几个sheet页  
        Workbook hssfWorkbook = ExcelUtil.getWorkBook(file);  
        StringBuilder sb=new StringBuilder(); 
        try {  
            ImportParams params = new ImportParams();  
            // 循环工作表Sheet  
            for (int numSheet = 0; numSheet < hssfWorkbook.getNumberOfSheets(); numSheet++) {  
                //表头在第几行 
				params.setTitleRows(0); 
				//距离表头中间有几行不要的数据  
				//params.setStartRows(1);  
                //第几个sheet页  
                params.setStartSheetIndex(numSheet);  
                //验证数据  
                params.setNeedVerfiy(true);  
                  
                //ExcelImportResult result=null;
                if(numSheet==0){  
                	ExcelImportResult result = ExcelImportUtil.importExcelMore(file.getInputStream(),ProjectPojo.class, params);
                	List list=null;
                    //如果有些数据验证出来有误   为true  
                    if(result.isVerfiyFail()){  
                        //不合规定的数据  
                        list=result.getFailList();  
                        //拼凑错误信息,自定义  
                        for(int i=0;i proList= ExcelImportUtil.importExcel(file.getInputStream(),ProjectPojo.class, params); 
                	System.out.println("***********导入数据:"+result.getList());
                	System.out.println("***********错误信息:"+sb.toString());
                     //插入验证合格的数据  
                     //CallServiceUtil.callDataService("", "", new Object[] { result.getList() },new Class[] { List.class });  
                }else if(numSheet==1){  
                	List feeList= ExcelImportUtil.importExcel(file.getInputStream(),FeePojo.class, params); 
                	System.out.println("***********导入数据:"+feeList);
                }else if(numSheet>1){  
                	List dataList= ExcelImportUtil.importExcel(file.getInputStream(),DataPojo.class, params);
                	System.out.println("***********导入数据:"+dataList);
                }
                
            }  
            if(sb.length()!=0){  
                return new JsonResult(sb.toString());  
            }  
        } catch (Exception e) {  
            e.printStackTrace();  
            return new JsonResult("导入失败!请检查导入文档的格式是否正确");  
        } 
        return new JsonResult(StatusUtil.SUCCESS,"导入成功!");  
    }
	
	
	//	导出
	@RequestMapping(value = "/excelExport", method = RequestMethod.POST)
	public void excelExport(HttpServletResponse response, @RequestParam Map params) throws IOException {
		
		//把要导出的信息放在map里面
		Map map = new HashMap();
		//获取信息
		/*// 员工信息
		List personList = CallServiceUtil.callDataService("personService", "excelExport",
				new Object[] { params }, new Class[] { Map.class });
		// 教育经历
		List educationList = CallServiceUtil.callDataService("educationService", "excelExport",
				new Object[] { params }, new Class[] { Map.class });
		//合同
		List contract = CallServiceUtil.callDataService("contractService", "excelExport",
				new Object[] { params }, new Class[] { Map.class });
		//往map里面存放信息
		map.put("person", personList);
		map.put("education", educationList);
		map.put("contract", contract);*/
		
		// 获取导出excel指定模版
		File fs = new File(this.getClass().getResource("/").getPath());
		// 文件存放目录   自定义
		String path = null;
		TemplateExportParams tep = new TemplateExportParams(path, true);
		//把map里面的信息放入模板
		Workbook workbook = ExcelExportUtil.exportExcel(tep, map);
		//下载
		ExcelUtil.downloadExcel(response, workbook, "人员信息");

	}

}

 模板需注意 

第一个:{{$fe: person t.**     最后一个:t.** }} 

日期格式化:fd:(t.partyDate;yyyy-MM-dd)

上面是使用模板的方式,下面介绍下不需要模板的方式(其实在上一篇中已经有写到这里简单写一下)

	/**
	 * 单Excel文件多sheet导出Excel数据(注意sheetMap的key需与对象数组中的对象名称一致)
	 * @param sheetMap map数据 如:sheetMap.put("PersonnelInfo",List);
	 * @param sheetName sheet名称数组 如:new String[] {"人员信息","家庭信息",...};
	 * @param objectClass 对象名称数组 如:new String[] {"PersonnelInfo","EducatInfo",...};
	 * @param goalName 文件名称
	 * @return 文件存储地址
	 * @throws Exception
	 */
	public String exportExcelManySheet(Map sheetMap,String[] sheetName,String[] objectClass,String goalName){
		
		//判断参数是否为空
		if (sheetName.length<1||objectClass.length<1||sheetMap==null||StringUtil.isNull(goalName)) {
			return null;
		}
		try {
			List> sheetsList = new ArrayList>() ;
			for (int i = 0; i < sheetName.length; i++) {
				//判断map和对象是否为空
				if (StringUtil.isNull(objectClass[i]) &&sheetMap.get(objectClass[i]) == null) {
					continue;
				}
		  		ExportParams exportParams = new ExportParams() ;
		  		exportParams.setSheetName(sheetName[i]);
		  		exportParams.setStyle(ExcelExportStyler.class);
		        Map exportMap = new HashMap();
		        exportMap.put("title",exportParams);
		        exportMap.put("entity",Class.forName("com.isoftstone.common.utils.excelUtil.entity."+objectClass[i]));
		        exportMap.put("data", sheetMap.get(objectClass[i]));
		        sheetsList.add(exportMap);
			}
			Workbook workbook = ExcelExportUtil.exportExcel(sheetsList, ExcelType.HSSF) ; 
			// 判断文件存放地址是否存在,没有则创建
			File savefile = new File(fileGoalUrl);
			if (!savefile.exists()) {
				logger.info("单Excel文件多sheet导出Excel数据的存储文件目录不存在,为您创建文件夹!");
				savefile.mkdirs();
			}
			goalName=fileGoalUrl+goalName+".xls";
			FileOutputStream fos = new FileOutputStream(goalName);
			workbook.write(fos);
			fos.close();
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("单Excel文件多sheet导出Excel数据异常:"+e);
			return null;
		}
		return goalName;
	}

 调用方式,以下只是一个测试类方法,详细请根据业务进行改造

        //人员信息汇总
        Map sheetMap=new  HashMap();
        List relatInfolist =new ArrayList();
        for (int i = 0; i < 2; i++) {
            RelatInfo relat=new RelatInfo();
            relat.setUserNo("B002"+i);
            relat.setSurname("Leon");
            relat.setTelephone("1387561245"+i);
            relatInfolist.add(relat);
        }
        List workHistorylist =new ArrayList();
        for (int i = 0; i < 3; i++) {
            WorkHistory work =new WorkHistory();
            work.setUserNo("A001"+i);
            work.setSurname("测试数据"+i);
            work.setBeginDate("2018/11/28");
            work.setEndDate("2018/11/28");
            work.setPosition("老板");
            work.setCorporateName("吹水无敌");
            workHistorylist.add(work);
        }
        sheetMap.put("RelatInfo", relatInfolist);
        sheetMap.put("WorkHistory", workHistorylist);
        String url=ex.exportExcelManeySheet(sheetMap,new String[]{"工作经历","家庭信息"},new String[]{"RelatInfo","WorkHistory"},"D:/入场人员信息汇总-测试.xls");
        System.out.println("文件地址:"+url);

希望对大家有用

 

你可能感兴趣的:(#,Java基础,JavaWeb开发基础,#,项目中的踩坑技术点)