java,excel实现单元格合并导入

需要导入excel的样子

java,excel实现单元格合并导入_第1张图片

代码:说明 最多支持5级目录导入

package net.parim.spark.unicom.provider.careercenter.service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
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;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import net.parim.spark.core.system.entity.UserGroup;
import net.parim.spark.core.system.security.UserToken;
import net.parim.spark.core.system.service.UserGroupService;
import net.parim.spark.unicom.provider.careercenter.entity.CareerTeachMaterial;

public class TeachingMaterialImport {
	public static final String UPLOADTEACHEXCEL ="TEACHEXCEL";
	public Workbook readFile(InputStream inputStream,String fileName){
		Workbook wb  = null; 
		Map map = new HashMap<>();
		boolean isE2007 = false;    //判断是否是excel2007格式    
        if(fileName.endsWith("xlsx")){  
            isE2007 = true;  
        }  
        try {
			InputStream input = inputStream;  //建立输入流    
			//根据文件格式(2003或者2007)来初始化    
			if(isE2007){   
			    wb = new XSSFWorkbook(input);  
			}else{    
			    wb = new HSSFWorkbook(input);  
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}  
        return wb;
	}

	/**
	 * 校检表头
	 */
	public Map inspectHead(Sheet sheet){
		//所有的单元格信息
		List cras = getCombineCell(sheet); 
		//存储行信息
		List> irs = new ArrayList<>(); 
		//表头只有2行
		for(int i = 0; i < 2;i++){ 
			 Row row = sheet.getRow(i);  //获取行
             Map map1 = new HashMap();  
             //存储列信息
             List> items = new ArrayList<>();    
             if(isMergedRegion(sheet,i,0)){ 
            	 int lastRow = getRowNum(cras,sheet.getRow(i).getCell(0),sheet);  
            	 for(;i<=lastRow;i++){  
                     row = sheet.getRow(i); 
                     int cellNum = row.getLastCellNum();//列数
                     Map map2 = new HashMap();
                     for(int ce=0;ce map3 = new HashMap();
                 for(int ce=0;ce> list = (ArrayList)irs.get(0).get("cell");//获取list的个数
       	 int catalogCount=0;
       	 Map save = new HashMap<>();
       	 Map saveGrade = new HashMap<>();
		 for(int s=0;s> getBody(Sheet sheet){
		List> all = new ArrayList<>();
		//所有的单元格信息
		List cras = getCombineCell(sheet);  
		//存储行信息
		List> irs = new ArrayList<>(); 
		int count = sheet.getLastRowNum()+1;//总行数  
		//表头只有2行
		for(int i = 2; i < count;i++){ 
			 Row row = sheet.getRow(i);  //获取行
             Map map1 = new HashMap();  
             //存储列信息
             List> items = new ArrayList<>();    
             if(isMergedRegion(sheet,i,0)){ 
            	 int lastRow = getRowNum(cras,sheet.getRow(i).getCell(0),sheet);  
            	 for(;i<=lastRow;i++){  
                     row = sheet.getRow(i); 
                     int cellNum = row.getLastCellNum();//列数
                     Map map2 = new HashMap();
                     for(int ce=0;ce map3 = new HashMap();
                 for(int ce=0;ce> list = (ArrayList)irs.get(a).get("cell");//获取list的个数
       	 if(list.size()>0){
       		 for(int b=0;b  
     */    
     public List getCombineCell(Sheet sheet)    
     {    
         List list = new ArrayList();    
         //获得一个 sheet 中合并单元格的数量    
         int sheetmergerCount = sheet.getNumMergedRegions();  
         //遍历所有的合并单元格    
         for(int i = 0; i= firstRow && row <= lastRow){    
              if(column >= firstColumn && column <= lastColumn){    
                  return true;    
              }    
          }  
        }    
        return false;    
      } 
      
      private int getRowNum(List listCombineCell,Cell cell,Sheet sheet){  
          int xr = 0;  
          int firstC = 0;    
          int lastC = 0;    
          int firstR = 0;    
          int lastR = 0;    
          for(CellRangeAddress ca:listCombineCell)    
          {  
              //获得合并单元格的起始行, 结束行, 起始列, 结束列    
              firstC = ca.getFirstColumn();    
              lastC = ca.getLastColumn();    
              firstR = ca.getFirstRow();    
              lastR = ca.getLastRow();    
              if(cell.getRowIndex() >= firstR && cell.getRowIndex() <= lastR)     
              {    
                  if(cell.getColumnIndex() >= firstC && cell.getColumnIndex() <= lastC)     
                  {    
                      xr = lastR;  
                  }   
              }    
                
          }  
          return xr;    
      }
      
      /**    
       * 获取单元格的值    
       * @param cell    
       * @return    
       */      
       public String getCellValue(Cell cell){      
           if(cell == null) return "";      
           if(cell.getCellType() == Cell.CELL_TYPE_STRING){      
               return cell.getStringCellValue();      
           }
           return "";      
       } 
       
       /**
        * 填充数据
        * @param list
        */
       public List> fillData(List> list){
    	   for(int i=0;i> splitData(Map map,List> list){
    	   List> all = new ArrayList<>();
    	   //获取总共的列数
    	   int colNum = list.get(0).size();
    	   //获取工种之前的列数
    	   Map catalogCount = (HashMap)map.get("saveGrade");
     	   int count = colNum-catalogCount.size();
    	   //1.循环list
    	   for(int i=0;i col = new HashMap<>();
        			   if((!list.get(i).get(j).toString().equals(""))&&j==0){
        				   col.put("parent", 1);
        			   }else{
        				   col.put("parent", list.get(i).get(jj-1).toString());
        			   }
        			   
        			   col.put("name", list.get(i).get(j));
        			   for(int a=(colNum-catalogCount.size());a> duplicateRemoval(List> list){
    	    List> result = new ArrayList>();
    	    result.add(list.get(0));
    	    for(int i=0;i> list){
    	    String add = "";
    	    Set set = new LinkedHashSet();
    	    for(int i=0;i> packingIdentity(Map gz,Map map,List> list){
    	   Map iscompulsoory = new HashMap<>();
    	   iscompulsoory.put("熟练掌握", 1);
    	   iscompulsoory.put("掌握", 1);
    	   iscompulsoory.put("熟悉", 0);
    	   iscompulsoory.put("了解", 0);
    	   iscompulsoory.put("不需要", 0);
    	   Map grade = (HashMap)map.get("saveGrade");
    	   for(int i=0;i list1 = new ArrayList<>();
    		   for (String key : list.get(i).keySet()) { 
    			   if(grade.containsKey(key)){
    				   if(gz.containsKey(grade.get(key))){
    				     list1.add(Long.valueOf(gz.get(grade.get(key)).toString()));
    				   }
    			   }
    		   }  
    		   List list2 = new ArrayList<>();
    		   int f=0;
    		   for (Object key : list.get(i).values()) { 
    			  
    			   if(iscompulsoory.containsKey(key)){
    				   list2.add(Long.valueOf(iscompulsoory.get(key).toString()));
    			   }
    		   }
    		   list.get(i).put("GZID", list1);//存储工种id
    		   list.get(i).put("GZIS", list2);//是否必修
    	   }
    	   return list;
       }
       
       /**
        * 将list解析成bean,进行存储信息(教材、工种)
        */
       public void analysisList2bean(List> list,CareerTeachManageService categoryService,UserToken userToken,UserGroupService userGroupService,Long userGroupId){
    	   //map 用来存储父类
    	   Map parent = new HashMap<>();
    	   for(int i=0;i gzid = (ArrayList)list.get(i).get("GZID");
    		  List gzis = (ArrayList)list.get(i).get("GZIS");
    		  for(int j=0;j isCom = new HashMap<>();
    			  isCom.put("cace_material_id_com", teach.getId());
    			  isCom.put("career_identiey_id", gzid.get(j));
    			  isCom.put("is_compulsoory", gzis.get(j));
    			  categoryService.insertIdentityIsCompulsory(isCom);
    		  }
    	   }
       }
       /**
        * 检查重复
        * @param sheet
        * @return
        */
       public String checkRepeat(Sheet sheet){
    	   TeachingMaterialImport ti = new TeachingMaterialImport();
    	   //1.获取body内容
    	   List> bodyList = ti.getBody(sheet);
    	   //2.将body中的null就行数据填充
    	   List> fillList = ti.fillData(bodyList);
    	   return ti.getRootCategory(fillList);
    	   
       }
       public void executeAllMethod(Sheet sheet,Map head,Map gz,CareerTeachManageService categoryService,UserToken userToken,UserGroupService userGroupService,Long userGroupId){
    	   TeachingMaterialImport ti = new TeachingMaterialImport();
    	  
    	   //1.获取body内容
    	   List> bodyList = ti.getBody(sheet);
    	   //2.将body中的null就行数据填充
    	   List> fillList = ti.fillData(bodyList);
    	   //3.拆分表格中的数据
    	   List> splitList = ti.splitData(head,fillList);
    	   //4.去除重复行
    	   List> duplicateList = ti.duplicateRemoval(splitList);
    	   //5.封装其中包含的工种id及是否必修
    	   List> packingList =ti.packingIdentity(gz,head, duplicateList);
    	   //6.将list封装成bean就行保存
    	   ti.analysisList2bean(packingList,categoryService,userToken,userGroupService,userGroupId);
       }
       
       public static void main(String[] args) throws FileNotFoundException {
   		File file=new File("d://111.xlsx");
   		InputStream is = new FileInputStream(file);
   		TeachingMaterialImport ti = new TeachingMaterialImport();
   		Workbook wb = ti.readFile(is, "111.xlsx");	
   		Sheet sheet = wb.getSheetAt(0);
   		Map map = ti.inspectHead(sheet);	
  		List> list = ti.getBody(sheet);
 	    List> fillList = ti.fillData(list);
 	   // Set set = ti.getRootCategory(fillList);
	    List> splitList = ti.splitData(map,fillList);
 	   	List> duplicateList = ti.duplicateRemoval(splitList);
//  		for(int i=0;i> list2 = ti.splitData(map,ti.fillData(list));
//   		List> list3 =ti.duplicateRemoval(list2);
   		//List> list4 =ti.packingIdentity(map, list3);
//   		for(int i=0;i

效果图

java,excel实现单元格合并导入_第2张图片

java,excel实现单元格合并导入_第3张图片

有喜欢的朋友可以关注下头条号《老徐聊技术》

你可能感兴趣的:(poi)