1. 程式人生 > >springboot+vue實現excel匯入-------去重

springboot+vue實現excel匯入-------去重

springboot後臺:


資料庫:

bean:
 

package com.heeexy.example.bean;

import java.util.Date;

//客戶列表
public class KH {
	
	private int id;	
	
	private int userId;
	
	private Date update_time;
	
	private Date create_time;
	
	private int dr=0;
	//客戶型別
	private String khlx;
	//客戶狀態
	private String khzt;
	//所屬部門
	private String ssbm;
	//客戶名稱
	private String khmc;
	//電話
	private double dianhua;
	//手機
	private double shouji;
	//地址
	private String dizhi;
	//最新跟進記錄
	private String zuixingenjinjilu;
	//前負責人
	private String qianfzr; 
	//計劃狀態
	private int status;
	//跟進日期
	private Date genjinriqi;
	//跟進內容
	private String genjinneirong;
	//發起日期
	private Date faqiriqi;
	//公司名稱
	private String gongsimingcheng;
	//公司地址
	private String gongsidizhi;
	//負責人
	private String fuzeren;
    //區分是我的客戶0還是下屬客戶1
	private int qfkh;
	
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public int getUserId() {
		return userId;
	}
	public void setUserId(int userId) {
		this.userId = userId;
	}
	public Date getUpdate_time() {
		return update_time;
	}
	public void setUpdate_time(Date update_time) {
		this.update_time = update_time;
	}
	public Date getCreate_time() {
		return create_time;
	}
	public void setCreate_time(Date create_time) {
		this.create_time = create_time;
	}
	
	public String getKhlx() {
		return khlx;
	}
	public void setKhlx(String khlx) {
		this.khlx = khlx;
	}
	public String getKhzt() {
		return khzt;
	}
	public void setKhzt(String khzt) {
		this.khzt = khzt;
	}
	public String getSsbm() {
		return ssbm;
	}
	public void setSsbm(String ssbm) {
		this.ssbm = ssbm;
	}
	
	public String getKhmc() {
		return khmc;
	}
	public void setKhmc(String khmc) {
		this.khmc = khmc;
	}
	
	public String getDizhi() {
		return dizhi;
	}
	public void setDizhi(String dizhi) {
		this.dizhi = dizhi;
	}
	public String getZuixingenjinjilu() {
		return zuixingenjinjilu;
	}
	public void setZuixingenjinjilu(String zuixingenjinjilu) {
		this.zuixingenjinjilu = zuixingenjinjilu;
	}
	public String getQianfzr() {
		return qianfzr;
	}
	public void setQianfzr(String qianfzr) {
		this.qianfzr = qianfzr;
	}

	public int getStatus() {
		return status;
	}
	public void setStatus(int status) {
		this.status = status;
	}

	public double getDianhua() {
		return dianhua;
	}
	public void setDianhua(double dianhua) {
		this.dianhua = dianhua;
	}
	public double getShouji() {
		return shouji;
	}
	public void setShouji(double shouji) {
		this.shouji = shouji;
	}
	public Date getGenjinriqi() {
		return genjinriqi;
	}
	public void setGenjinriqi(Date genjinriqi) {
		this.genjinriqi = genjinriqi;
	}
	public String getGenjinneirong() {
		return genjinneirong;
	}
	public void setGenjinneirong(String genjinneirong) {
		this.genjinneirong = genjinneirong;
	}
	public Date getFaqiriqi() {
		return faqiriqi;
	}
	public void setFaqiriqi(Date faqiriqi) {
		this.faqiriqi = faqiriqi;
	}
	public String getGongsimingcheng() {
		return gongsimingcheng;
	}
	public void setGongsimingcheng(String gongsimingcheng) {
		this.gongsimingcheng = gongsimingcheng;
	}
	public String getGongsidizhi() {
		return gongsidizhi;
	}
	public void setGongsidizhi(String gongsidizhi) {
		this.gongsidizhi = gongsidizhi;
	}
	public String getFuzeren() {
		return fuzeren;
	}
	public void setFuzeren(String fuzeren) {
		this.fuzeren = fuzeren;
	}
	public int getDr() {
		return dr;
	}
	public void setDr(int dr) {
		this.dr = dr;
	}
	public int getQfkh() {
		return qfkh;
	}
	public void setQfkh(int qfkh) {
		this.qfkh = qfkh;
	}
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((create_time == null) ? 0 : create_time.hashCode());
		long temp;
		temp = Double.doubleToLongBits(dianhua);
		result = prime * result + (int) (temp ^ (temp >>> 32));
		result = prime * result + ((dizhi == null) ? 0 : dizhi.hashCode());
		result = prime * result + dr;
		result = prime * result + ((faqiriqi == null) ? 0 : faqiriqi.hashCode());
		result = prime * result + ((fuzeren == null) ? 0 : fuzeren.hashCode());
		result = prime * result + ((genjinneirong == null) ? 0 : genjinneirong.hashCode());
		result = prime * result + ((genjinriqi == null) ? 0 : genjinriqi.hashCode());
		result = prime * result + ((gongsidizhi == null) ? 0 : gongsidizhi.hashCode());
		result = prime * result + ((gongsimingcheng == null) ? 0 : gongsimingcheng.hashCode());
		result = prime * result + id;
		result = prime * result + ((khlx == null) ? 0 : khlx.hashCode());
		result = prime * result + ((khmc == null) ? 0 : khmc.hashCode());
		result = prime * result + ((khzt == null) ? 0 : khzt.hashCode());
		result = prime * result + qfkh;
		result = prime * result + ((qianfzr == null) ? 0 : qianfzr.hashCode());
		temp = Double.doubleToLongBits(shouji);
		result = prime * result + (int) (temp ^ (temp >>> 32));
		result = prime * result + ((ssbm == null) ? 0 : ssbm.hashCode());
		result = prime * result + status;
		result = prime * result + ((update_time == null) ? 0 : update_time.hashCode());
		result = prime * result + userId;
		result = prime * result + ((zuixingenjinjilu == null) ? 0 : zuixingenjinjilu.hashCode());
		return result;
	}
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		KH other = (KH) obj;
		if (create_time == null) {
			if (other.create_time != null)
				return false;
		} else if (!create_time.equals(other.create_time))
			return false;
		if (Double.doubleToLongBits(dianhua) != Double.doubleToLongBits(other.dianhua))
			return false;
		if (dizhi == null) {
			if (other.dizhi != null)
				return false;
		} else if (!dizhi.equals(other.dizhi))
			return false;
		if (dr != other.dr)
			return false;
		if (faqiriqi == null) {
			if (other.faqiriqi != null)
				return false;
		} else if (!faqiriqi.equals(other.faqiriqi))
			return false;
		if (fuzeren == null) {
			if (other.fuzeren != null)
				return false;
		} else if (!fuzeren.equals(other.fuzeren))
			return false;
		if (genjinneirong == null) {
			if (other.genjinneirong != null)
				return false;
		} else if (!genjinneirong.equals(other.genjinneirong))
			return false;
		if (genjinriqi == null) {
			if (other.genjinriqi != null)
				return false;
		} else if (!genjinriqi.equals(other.genjinriqi))
			return false;
		if (gongsidizhi == null) {
			if (other.gongsidizhi != null)
				return false;
		} else if (!gongsidizhi.equals(other.gongsidizhi))
			return false;
		if (gongsimingcheng == null) {
			if (other.gongsimingcheng != null)
				return false;
		} else if (!gongsimingcheng.equals(other.gongsimingcheng))
			return false;
		if (id != other.id)
			return false;
		if (khlx == null) {
			if (other.khlx != null)
				return false;
		} else if (!khlx.equals(other.khlx))
			return false;
		if (khmc == null) {
			if (other.khmc != null)
				return false;
		} else if (!khmc.equals(other.khmc))
			return false;
		if (khzt == null) {
			if (other.khzt != null)
				return false;
		} else if (!khzt.equals(other.khzt))
			return false;
		if (qfkh != other.qfkh)
			return false;
		if (qianfzr == null) {
			if (other.qianfzr != null)
				return false;
		} else if (!qianfzr.equals(other.qianfzr))
			return false;
		if (Double.doubleToLongBits(shouji) != Double.doubleToLongBits(other.shouji))
			return false;
		if (ssbm == null) {
			if (other.ssbm != null)
				return false;
		} else if (!ssbm.equals(other.ssbm))
			return false;
		if (status != other.status)
			return false;
		if (update_time == null) {
			if (other.update_time != null)
				return false;
		} else if (!update_time.equals(other.update_time))
			return false;
		if (userId != other.userId)
			return false;
		if (zuixingenjinjilu == null) {
			if (other.zuixingenjinjilu != null)
				return false;
		} else if (!zuixingenjinjilu.equals(other.zuixingenjinjilu))
			return false;
		return true;
	}
	@Override
	public String toString() {
		return "KH [id=" + id + ", userId=" + userId + ", update_time=" + update_time + ", create_time=" + create_time
				+ ", dr=" + dr + ", khlx=" + khlx + ", khzt=" + khzt + ", ssbm=" + ssbm + ", khmc=" + khmc
				+ ", dianhua=" + dianhua + ", shouji=" + shouji + ", dizhi=" + dizhi + ", zuixingenjinjilu="
				+ zuixingenjinjilu + ", qianfzr=" + qianfzr + ", status=" + status + ", genjinriqi=" + genjinriqi
				+ ", genjinneirong=" + genjinneirong + ", faqiriqi=" + faqiriqi + ", gongsimingcheng=" + gongsimingcheng
				+ ", gongsidizhi=" + gongsidizhi + ", fuzeren=" + fuzeren + ", qfkh=" + qfkh + "]";
	}
	public KH(int id, int userId, Date update_time, Date create_time, int dr, String khlx, String khzt, String ssbm,
			String khmc, double dianhua, double shouji, String dizhi, String zuixingenjinjilu, String qianfzr,
			int status, Date genjinriqi, String genjinneirong, Date faqiriqi, String gongsimingcheng,
			String gongsidizhi, String fuzeren, int qfkh) {
		super();
		this.id = id;
		this.userId = userId;
		this.update_time = update_time;
		this.create_time = create_time;
		this.dr = dr;
		this.khlx = khlx;
		this.khzt = khzt;
		this.ssbm = ssbm;
		this.khmc = khmc;
		this.dianhua = dianhua;
		this.shouji = shouji;
		this.dizhi = dizhi;
		this.zuixingenjinjilu = zuixingenjinjilu;
		this.qianfzr = qianfzr;
		this.status = status;
		this.genjinriqi = genjinriqi;
		this.genjinneirong = genjinneirong;
		this.faqiriqi = faqiriqi;
		this.gongsimingcheng = gongsimingcheng;
		this.gongsidizhi = gongsidizhi;
		this.fuzeren = fuzeren;
		this.qfkh = qfkh;
	}
	public KH() {
		super();
		// TODO Auto-generated constructor stub
	}
	

	

	
	
	

}

mapper:
 

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.heeexy.example.dao.KHDao">

	<resultMap type="com.heeexy.example.bean.KH" id="Map1">
		<id column="id" property="id" />
		<result column="userId" property="userId" />
		<result column="update_time" property="update_time" />
		<result column="create_time" property="create_time" />
		<result column="dr" property="dr" />
		<result column="khlx" property="khlx" />
		<result column="khzt" property="khzt" />
		<result column="ssbm" property="ssbm" />
		<result column="khmc" property="khmc" />
		<result column="dianhua" property="dianhua" />
		<result column="shouji" property="shouji" />
		<result column="dizhi" property="dizhi" />
		<result column="zuixingenjinjilu" property="zuixingenjinjilu" />
		<result column="qianfzr" property="qianfzr" />
		<result column="status" property="status" />
		<result column="genjinriqi" property="genjinriqi" />
		<result column="genjinneirong" property="genjinneirong" />
		<result column="faqiriqi" property="faqiriqi" />
		<result column="gongsimingcheng" property="gongsimingcheng" />
		<result column="gongsidizhi" property="gongsidizhi" />
		<result column="fuzeren" property="fuzeren" />
	    <result column="qfkh" property="qfkh" />

	</resultMap>

	<resultMap type="com.heeexy.example.bean.KH" id="KHMap">
		<id column="id" property="id" />
		<result column="userId" property="userId" />
		<result column="update_time" property="update_time" />
		<result column="create_time" property="create_time" />
		<result column="dr" property="dr" />
		<result column="khlx" property="khlx" />
		<result column="khzt" property="khzt" />
		<result column="ssbm" property="ssbm" />
		<result column="khmc" property="khmc" />
		<result column="dianhua" property="dianhua" />
		<result column="shouji" property="shouji" />
		<result column="dizhi" property="dizhi" />
		<result column="zuixingenjinjilu" property="zuixingenjinjilu" />
		<result column="qianfzr" property="qianfzr" />
		<result column="status" property="status" />
		<result column="genjinriqi" property="genjinriqi" />
		<result column="genjinneirong" property="genjinneirong" />
		<result column="faqiriqi" property="faqiriqi" />
		<result column="gongsimingcheng" property="gongsimingcheng" />
		<result column="gongsidizhi" property="gongsidizhi" />
		<result column="fuzeren" property="fuzeren" />
		<result column="qfkh" property="qfkh" />
		<collection property="domains" ofType="com.alibaba.fastjson.JSONObject">
			<id column="id" property="id" />
			<result column="userId" property="userId" />
			<result column="update_time" property="update_time" />
			<result column="create_time" property="create_time" />
			<result column="drt" property="drt" />
			<result column="lianxiren" property="lianxiren" />
			<result column="status" property="status" />
			<result column="kehuId" property="kehuId" />
		</collection>
		<collection property="domainsXGJ" ofType="com.alibaba.fastjson.JSONObject">
			<id column="id" property="id" />
			<result column="userId" property="userId" />
			<result column="update_time" property="update_time" />
			<result column="create_time" property="create_time" />
			<result column="dr" property="dr" />
			<result column="dianhua" property="dianhua" />
			<result column="lianxiren" property="lianxiren" />
            <result column="genjinzhuangtai" property="genjinzhuangtai" />
			<result column="xiacigenjinshijian" property="xiacigenjinshijian" />
			<result column="genjinriqi" property="genjinriqi" />
			<result column="khmc" property="khmc" />
			<result column="genjinneirong" property="genjinneirong" />
			<result column="khId" property="khId" />

		</collection>
		
	</resultMap>



	<!-- excel匯出 -->
	<select id="findAll" resultType="List" resultMap="Map1">
	   select * from kh 
	</select>

	<!-- excel匯入 -->
	<insert id="addKHexcel" parameterType="com.heeexy.example.bean.KH" > 
	INSERT INTO kh (gongsimingcheng,gongsidizhi,khmc,khlx,dianhua,shouji,dizhi,zuixingenjinjilu,qianfzr,khzt,genjinriqi,genjinneirong,faqiriqi,fuzeren,dr) VALUES (#{gongsimingcheng},#{gongsidizhi},#{khmc},#{khlx},#{dianhua},#{shouji},#{dizhi},#{zuixingenjinjilu},#{qianfzr},#{khzt},#{genjinriqi},#{genjinneirong},#{faqiriqi},#{fuzeren},#{dr}) 
	</insert>

	<!-- excel匯入去重 -->
	<select id="countquc" resultType="Integer">
		SELECT count(*)
		FROM
		kh w
		WHERE w.dr = '0' and khmc = #{khmc} and shouji = #{shouji} and gongsimingcheng = #{gongsimingcheng}
	</select>





	





</mapper>

dao:

   //excel匯出
	public List<KH> findAll();

	
	
	//excel匯入
	public void addKHexcel(KH sysKH);
	
	//excel匯入去重
	public int countquc(@Param("khmc") String khmc,@Param("shouji") Double shouji,@Param("gongsimingcheng") String gongsimingcheng);

service:

 //excel匯出
    public List<KH> findAll();


    
    //excel匯入
    public String batchImport(String fileName, MultipartFile file) throws Exception;

serviceImpl:

package com.heeexy.example.service.impl;

import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.*;
import java.util.Map;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
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.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.druid.sql.dialect.oracle.ast.stmt.OracleIfStatement.Else;
import com.alibaba.fastjson.JSONObject;
import com.heeexy.example.bean.DD;
import com.heeexy.example.bean.KH;
import com.heeexy.example.bean.LianXiRen;
import com.heeexy.example.bean.MX;
import com.heeexy.example.bean.XGJ;
import com.heeexy.example.dao.KHDao;
import com.heeexy.example.service.KHService;
import com.heeexy.example.util.CommonUtil;

import net.bytebuddy.description.field.FieldDescription.InGenericShape;

@Service
public class KHServiceImpl implements KHService {
	
	@Autowired
	private KHDao khDao;
	
	
	
	
	/**
	 * id放入list
	 * 
	 * @param id
	 *            id(多個已逗號分隔)
	 * @return List集合
	 * declareAd
	 */
	public List<String> getList(String id) {
		List<String> list = new ArrayList<String>();
		
		String[] str = id.split(",");
		for (int i = 0; i < str.length; i++) {
			list.add(str[i]);
		}
		return list;
	
	}
	
	  

		
		/**
		 * 匯出excel
		 */
		@Override
		public List<KH> findAll() {
			// TODO Auto-generated method stub
			 List<KH> list = khDao.findAll();
			 return list;
		}
		
		/**
		 * excel匯入
		 */
		private final static String XLS = "xls";
		private final static String XLSX = "xlsx";
		@Transactional(readOnly = false,rollbackFor = Exception.class)
	    @Override
	    public String batchImport(String fileName, MultipartFile file) throws Exception {
	 
//	        if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
//	            throw new Exception("上傳檔案格式不正確");
//	        }      
		       
	        List<KH> khs = new ArrayList<>();
	      try{
	    	  InputStream is = file.getInputStream();
	    	  //HSSFWorkbook workbook = new HSSFWorkbook(new POIFSFileSystem(is));
	    	  Workbook workbook = null;  
	    	  if(fileName.endsWith(XLS)){
	    		  workbook = new HSSFWorkbook(is);
		        }else if(fileName.endsWith(XLSX)){
		        	workbook = new XSSFWorkbook(is);
		        }else{
		        	return "上傳檔案格式不正確";
		        }
	            //有多少個sheet
	            int sheets = workbook.getNumberOfSheets();
	            
	            for (int i = 0; i < sheets; i++) {
	                //HSSFSheet sheet = workbook.getSheetAt(i);
	            	//獲得當前sheet工作表  
	                Sheet sheet = workbook.getSheetAt(i);  
	                if(sheet == null){  
	                    continue;  
	                }  
	                //獲取多少行
	                int rows = sheet.getPhysicalNumberOfRows();
	                KH kh = null;
	                //遍歷每一行,注意:第 0 行為標題
	                System.out.println("1234456576879");
	                System.out.println("進入遍歷方法");
	                for (int j = 1; j < rows; j++) {
	                	kh = new KH();
	                     //獲得第 j 行	                    
	                    //HSSFRow row = sheet.getRow(j);
	                	Row row = sheet.getRow(j);  
	                    System.out.println("row="+row.getCell(0));
	                    
	                    kh.setGongsimingcheng(row.getCell(0).getStringCellValue());
	                    System.out.println("getGongsimingcheng="+ kh.getGongsimingcheng());
	                    kh.setGongsidizhi(row.getCell(1).getStringCellValue());
	                    System.out.println("getGongsidizhi="+ kh.getGongsidizhi());
	                    kh.setKhmc(row.getCell(2).getStringCellValue());
	                    System.out.println("getKhmc="+ kh.getKhmc());
	                    kh.setKhlx(row.getCell(3).getStringCellValue());
	                    System.out.println("getKhlx="+ kh.getKhlx());
	                    kh.setDianhua(row.getCell(4).getNumericCellValue());
	                    System.out.println("getDianhua="+ kh.getDianhua());
	                    kh.setShouji(row.getCell(5).getNumericCellValue());
	                    System.out.println("getShouji="+ kh.getShouji());
	                    kh.setDizhi(row.getCell(6).getStringCellValue());
	                    System.out.println("getDizhi="+ kh.getDizhi());
	                    kh.setZuixingenjinjilu(row.getCell(7).getStringCellValue());
	                    System.out.println("getZuixingenjinjilu="+ kh.getZuixingenjinjilu());
	                    kh.setQianfzr(row.getCell(8).getStringCellValue());
	                    System.out.println("getQianfzr="+ kh.getQianfzr());
	                    kh.setKhzt(row.getCell(9).getStringCellValue());
	                    System.out.println("getKhzt="+ kh.getKhzt());
	                    kh.setGenjinriqi(row.getCell(10).getDateCellValue());
	                    System.out.println("getGenjinriqi="+ kh.getGenjinriqi());
	                    kh.setGenjinneirong(row.getCell(11).getStringCellValue());
	                    System.out.println("getGenjinneirong="+ kh.getGenjinneirong());
	                    kh.setFaqiriqi(row.getCell(12).getDateCellValue());
	                    System.out.println("getFaqiriqi="+ kh.getFaqiriqi());
	                    kh.setFuzeren(row.getCell(13).getStringCellValue());  
	                    System.out.println("getFuzeren="+ kh.getFuzeren());
	                   
	                    System.out.println("做excel去重判斷");
	                   int count =  khDao.countquc(kh.getKhmc(),kh.getShouji(),kh.getGongsimingcheng());
	                  if(count>0){
	                	  
	                  }else{
	                	    khs.add(kh);
		                    System.out.println("khs="+khs.size());
		                    System.out.println("結束");
		                    System.out.println("退出迴圈");
			                khDao.addKHexcel(kh);
			                System.out.println("----------------"); 
	                  }
	                    
	                   
	                   
	                }                
	            
	            }
	        }catch(Exception e){
	        	return "匯入資料格式有誤,請檢查上傳檔案";
	        }
	        return "匯入資料成功";
	    }
		
		
		


	
	
}

controller:

package com.heeexy.example.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import com.alibaba.fastjson.JSONObject;
import com.heeexy.example.bean.DD;
import com.heeexy.example.bean.KH;
import com.heeexy.example.bean.LianXiRen;
import com.heeexy.example.bean.MX;
import com.heeexy.example.bean.XGJ;
import com.heeexy.example.service.EmailService;
import com.heeexy.example.service.KHService;
import com.heeexy.example.util.CommonUtil;
import com.sun.tools.javac.main.Main.Result;

@RestController
@RequestMapping("/kh")
@CrossOrigin
@ResponseBody
public class KHController {

	@Autowired
	private KHService khService;
	
	@Autowired
	private EmailService emailService;
	
	@Autowired
	private TemplateEngine templateEngine;
	


	/**
	 * 匯出excel
	 */
	
//	  @RequiresPermissions("kh:download") 
//	  @PostMapping("/download") public void download(HttpServletRequest
//	  request,HttpServletResponse response) throws IOException{
//	  
//	  HSSFWorkbook workbook = new HSSFWorkbook(); //建立一個Excel表單,引數為sheet的名字
//	  HSSFSheet sheet = workbook.createSheet("CRM客戶匯出");
//	  
//	  //建立表頭 
//	  setTitle(workbook, sheet); 
//	  List<KH> khs = khService.findAll();
//	  
//	  //新增資料行,並且設定單元格資料 
//	  int rowNum = 1; 
//	  for (KH kh:khs) { 
//		  HSSFRow row = sheet.createRow(rowNum);
//
//	  row.createCell(0).setCellValue(kh.getGongsimingcheng());
//	  row.createCell(1).setCellValue(kh.getGongsidizhi());
//	  row.createCell(2).setCellValue(kh.getKhmc());
//	  row.createCell(3).setCellValue(kh.getKhlx());
//	  row.createCell(4).setCellValue(kh.getDianhua());
//	  row.createCell(5).setCellValue(kh.getShouji());
//	  row.createCell(6).setCellValue(kh.getDizhi());
//	  row.createCell(7).setCellValue(kh.getZuixingenjinjilu());
//	  row.createCell(8).setCellValue(kh.getQianfzr());
//	  row.createCell(9).setCellValue(kh.getKhzt());
//	  row.createCell(10).setCellValue(kh.getGenjinriqi());
//	  row.createCell(11).setCellValue(kh.getGenjinneirong());
//	  row.createCell(12).setCellValue(kh.getFaqiriqi());
//	  row.createCell(13).setCellValue(kh.getFuzeren()); 
//	  rowNum++; 
//	  }
//	  
//	  String fileName = "D://CRM客戶匯出.xlsx"; 
//	  //清空response 
//	  response.reset();
//	  //設定response的Header 
//	  response.addHeader("Content-Disposition",
//	  "attachment;filename="+ fileName); OutputStream os = new
//	  BufferedOutputStream(response.getOutputStream());
//	  response.setContentType("application/vnd.ms-excel;charset=utf-8");
//	  //將excel寫入到輸出流中 
//	  workbook.write(os); 
//	  os.flush(); 
//	  os.close(); 
//	  }
//	  
//	 /***
//		 * 設定表頭
//		 * 
//		 * @param workbook
//		 * @param sheet
//		 */
//		  private void setTitle(HSSFWorkbook workbook, HSSFSheet sheet){
//		  HSSFRow row = sheet.createRow(0);
//		  //設定列寬,setColumnWidth的第二個引數要乘以256,這個引數的單位是1/256個字元寬度
//		  sheet.setColumnWidth(0, 10*256); sheet.setColumnWidth(1, 20*256);
//		  sheet.setColumnWidth(2, 20*256); sheet.setColumnWidth(3, 100*256);
//		  
//		  //設定為居中加粗 
//		  HSSFCellStyle style = workbook.createCellStyle(); HSSFFont
//		  font = workbook.createFont(); font.setBold(true);
//		  style.setFont(font);
//		  
//		  HSSFCell cell; 
//		  /*cell = row.createCell(0); cell.setCellValue("序號");
//		  cell.setCellStyle(style);*/
//		  
//		  cell = row.createCell(0); cell.setCellValue("公司名稱");
//		  cell.setCellStyle(style);
//		  
//		  cell = row.createCell(1); cell.setCellValue("公司地址");
//		  cell.setCellStyle(style);
//		  
//		  cell = row.createCell(2); cell.setCellValue("客戶名稱");
//		  cell.setCellStyle(style);
//		 
//		  cell = row.createCell(3); cell.setCellValue("客戶型別");
//		  cell.setCellStyle(style);
//		  
//		  cell = row.createCell(4); cell.setCellValue("電話");
//		  cell.setCellStyle(style);
//		  
//		  cell = row.createCell(5); cell.setCellValue("手機");
//		  cell.setCellStyle(style);
//		  
//		  cell = row.createCell(6); cell.setCellValue("地址");
//		  cell.setCellStyle(style);
//		  
//		  cell = row.createCell(7); cell.setCellValue("最新跟進記錄");
//		  cell.setCellStyle(style);
//		  
//		  cell = row.createCell(8); cell.setCellValue("前負責人");
//		  cell.setCellStyle(style);
//		  
//		  cell = row.createCell(9); cell.setCellValue("客戶狀態");
//		  cell.setCellStyle(style);
//		  
//		  cell = row.createCell(10); cell.setCellValue("跟進日期");
//		  cell.setCellStyle(style);
//		  
//		  cell = row.createCell(11); cell.setCellValue("跟進內容");
//		  cell.setCellStyle(style);
//		  
//		  cell = row.createCell(12); cell.setCellValue("發起日期");
//		  cell.setCellStyle(style);
//		  
//		  cell = row.createCell(13); cell.setCellValue("負責人");
//		  cell.setCellStyle(style);
//		  
//		  }
//		

	/**
	 * excel匯入
	 */

	@RequiresPermissions("kh:upload")
	@PostMapping("/upload")
	public String addKHexcel(@RequestParam("file") MultipartFile file) throws Exception {
		String fileName = file.getOriginalFilename();
		String test = khService.batchImport(fileName, file);
		System.out.println("test=" + test);
		return test;
	}




	
}

許可權:

vue:
 

 <el-button type="primary" icon="edit" v-if="hasPerm('kh:upload')" @click="submit($event)">excel匯入</el-button> 
          <input type="file"  @change="getFile($event)">
<el-button type="primary" icon="edit" :disabled="this.sels.length === 0"  v-if="hasPerm('kh:download')" @click="inportexcel()">excel匯出</el-button>

methods:{


    //excel匯入開始
     getFile: function (event) {
        this.file = event.target.files[0];
        this.file.name
        console.log(this.file);
      },
      submit: function (event) {
        if(this.file == null){
          alert("檔案為空,請選擇檔案進行匯入");
        }
        //阻止元素髮生預設的行為
        event.preventDefault();
        let formData = new FormData();
        formData.append("file", this.file);
         var url = this.HOST + "/kh/upload";
        axios.post(url, formData)
          .then(function (response) {
            alert(response.data);
            console.log(response);
            window.location.reload();
          })
          .catch(function (error) {
            alert("上傳失敗,請核對excel表格資料");
            console.log(error);
            alert(error);
            window.location.reload();
          });
      },
   
    //excel匯入結束

     //excel匯出開始
            inportexcel: function() { //相容ie10哦!
                        require.ensure([], () => {        
                        const { export_json_to_excel } = require('../../excel/Export2Excel');  //引入檔案      
                        const tHeader = ['公司名稱', '公司地址', '客戶名稱','客戶型別','電話','手機','地址','最新跟進記錄','前負責人','客戶狀態','跟進日期','跟進內容','發起日期','負責人']; // 匯出的表頭名        
                        const filterVal = ['gongsimingcheng','gongsidizhi','khmc','khlx', 'dianhua','shouji','dizhi','zuixingenjinjilu','qianfzr','genjinneirong','faqiriqi','fuzeren']; // 匯出的表頭欄位名
                        const list = this.sels;  
                        //const list = this.tableData; 
                        const data = this.formatJson(filterVal, list);        
                        export_json_to_excel(tHeader, data, 'CRM客戶匯出');      
                        }) .catch(err => {
                        console.log("sadasdaINPORTEXCEL");
                      });
 
                 },
                 formatJson(filterVal, jsonData) {
                 return jsonData.map(v => filterVal.map(j => v[j]))
             },
            //  exceldownload() {
            //       this.api({
            //         url: "/kh/download",
            //         method: "post",
            //         data: this.tempKH
            //       }).then(() => {
            //         this.getList();
            //         this.dialogFormVisible = false;
            //       });
            //     },
    //excel匯出結束

}

參考文章:
https://www.cnblogs.com/sprinkle/p/6426204.html