1. 程式人生 > >SpringBoot2 整合匯入和匯出

SpringBoot2 整合匯入和匯出

1、pom檔案加入,此處目前測試3.0.3版本可以無bug,3.2.0不行

<!-- 匯入和匯出-->
		<dependency>
			<groupId>cn.afterturn</groupId>
			<artifactId>easypoi-base</artifactId>
			<version>3.0.3</version>
		</dependency>
		<dependency>
			<groupId>cn.afterturn</groupId>
			<artifactId>easypoi-web</artifactId>
			<version>3.0.3</version>
		</dependency>
		<dependency>
			<groupId>cn.afterturn</groupId>
			<artifactId>easypoi-annotation</artifactId>
			<version>3.0.3</version>
		</dependency>


2、

編寫實體類

  • 此處注意必須要有空建構函式,否則會報錯“物件建立錯誤”
  • 關於註解@Excel,其他還有@ExcelCollection,@ExcelEntity ,@ExcelIgnore,@ExcelTarget等,此處我們用不到,可以去官方檢視更多

3、實體類
 

package com.ps.uzkefu.apps.callcenter.entity;

import java.text.SimpleDateFormat;
import java.util.Date;

import cn.afterturn.easypoi.excel.annotation.Excel;
import cn.afterturn.easypoi.excel.annotation.ExcelTarget;
import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.annotations.TableName;
import com.ps.uzkefu.base.BaseEntity;
import com.ps.uzkefu.util.DateUtil;

/**
 * <p>
 * 通話記錄
 * </p>
 *
 * @author ZhuShangJin
 * @since 2018-06-27
 */
@TableName("t_call_call_record")
@ExcelTarget("id")
public class CallRecord extends BaseEntity<CallRecord> {

    private static final long serialVersionUID = 1L;

    /**
     * 外呼或來電的唯一id
     */
    @TableField("call_id")
    public String callId;
    /**
     * 坐席的使用者id
     */
    @TableField("user_name")
    public String userName;
    /**
     * 呼叫型別 0:撥出 1:呼入 
     */
    @TableField("call_type")
    public int callType;
    /**
     * 主叫號碼
     */
    @TableField("from_num")
    @Excel(name = "來電號碼")
    public String fromNum;
    /**
     * 被叫號碼
     */
    @TableField("to_num")
    public String toNum;
    /**
     * 呼叫開始時間
     */
    @Excel(name = "來電時間", format = "yyyy-MM-dd HH:mm:ss")
    @TableField("call_time")
    public Date callTime;
    /**
     * ivr語音導航開始時間
     */
    @TableField("ivr_time")
    public Date ivrTime;
    /**
     * 應答時間
     */
    @TableField("answered_time")
    public Date answeredTime;
    /**
     * 掛機時間
     */
    @Excel(name = "結束通話時間",format = "yyyy-MM-dd HH:mm:ss")
    @TableField("hangup_time")
    public Date hangupTime;
    /**
     * 振鈴時長
     */
    @Excel(name = "振鈴時長(秒)")
    @TableField("ring_length")
    public int ringLength;
    /**
     * ivr語音導航時長
     */
    @TableField("ivr_length")
    public int ivrLength;
    /**
     * 來電在佇列中等待的時間
     */
    @TableField("queue_length")
    public int queueLength;
    /**
     * 通話時長
     */
    @TableField("talk_length")
    public Integer talkLength;
    /**
     * 通話錄音檔案
     */
    public String record;
    /**
     * 使用者滿意度 -1:未評價 其餘為使用者評價時的按鍵
     */
    @Excel(name = "滿意度",replace =  {"未評價_1", "不滿意_2"})
    public Integer satisfaction;
    /**
     * 分機號碼
     */
    @TableField("extension_num")
    public int extensionNum;
    /**
     * 中繼號
     */
    @TableField("trunk_num")
    public String trunkNum;
    /**
     * 客戶id
     */
    @TableField("customer_id")
    public String customerId;
    /**
     * 客戶電話
     */
    @TableField("customer_phone")
    public String customerPhone;
    /**
     * 客戶電話歸屬地
     */
    @TableField("customer_city")
    public String customerCity;

    @TableField("group_num")
    public  int groupNum;

    @TableField("queue_time")
    public Date queueTime;
    @TableField("ring_time")
    public Date ringTime;
    @TableField("customer_province")
    public String customerProvince;
    @TableField(exist = false)
    private String callTimeStart;
    @TableField(exist = false)
    private String talkLengthStart;

    @TableField(exist = false)
    private String callTimeEnd;
    @TableField(exist = false)
    private String talkLengthEnd;
    @TableField(exist = false)
    private String callTimeText;
    @TableField(exist = false)
    private String hangupTimeText;
    @TableField(exist = false)
    private  String province;
    @TableField(exist = false)
    private  String city;
    @TableField("handle_time")
    private Date handleTime; //呼損處理時間
    @TableField("handle_status")
    private Integer handleStatus; //呼損處理狀態  0 未處理   1 已處理

    @TableField(exist = false)
    private String handleTimeText;
    @TableField(exist = false)
    private String satisfactionText;
    @TableField(exist = false)
    private String handleStatusText;


    public String getCallId() {
        return callId;
    }

    public String getUserName() {
        return userName;
    }

    public int getCallType() {
        return callType;
    }

    public String getFromNum() {
        return fromNum;
    }

    public String getToNum() {
        return toNum;
    }

    public Date getCallTime() {
        return callTime;
    }

    public Date getIvrTime() {
        return ivrTime;
    }

    public Date getAnsweredTime() {
        return answeredTime;
    }

    public Date getHangupTime() {
        return hangupTime;
    }

    public int getRingLength() {
        return ringLength;
    }

    public int getIvrLength() {
        return ivrLength;
    }

    public int getQueueLength() {
        return queueLength;
    }

    public Integer getTalkLength() {
        return talkLength;
    }

    public String getRecord() {
        return record;
    }

    public Integer getSatisfaction() {
        return satisfaction;
    }

    public int getExtensionNum() {
        return extensionNum;
    }

    public String getTrunkNum() {
        return trunkNum;
    }

    public String getCustomerId() {
        return customerId;
    }

    public String getCustomerPhone() {
        return customerPhone;
    }

    public String getCustomerCity() {
        return customerCity;
    }

    public int getGroupNum() {
        return groupNum;
    }

    public Date getQueueTime() {
        return queueTime;
    }

    public Date getRingTime() {
        return ringTime;
    }

    public String getCustomerProvince() {
        return customerProvince;
    }

    public String getCallTimeStart() {
        return callTimeStart;
    }

    public String getTalkLengthStart() {
        return talkLengthStart;
    }

    public String getCallTimeEnd() {
        return callTimeEnd;
    }

    public String getTalkLengthEnd() {
        return talkLengthEnd;
    }

    public String getCallTimeText() {
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(callTime);
    }

    public String getHangupTimeText() {
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(hangupTime);
    }

    public void setCallId(String callId) {
        this.callId = callId;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public void setCallType(int callType) {
        this.callType = callType;
    }

    public void setFromNum(String fromNum) {
        this.fromNum = fromNum;
    }

    public void setToNum(String toNum) {
        this.toNum = toNum;
    }

    public void setCallTime(Date callTime) {
        this.callTime = callTime;
    }

    public void setIvrTime(Date ivrTime) {
        this.ivrTime = ivrTime;
    }

    public void setAnsweredTime(Date answeredTime) {
        this.answeredTime = answeredTime;
    }

    public void setHangupTime(Date hangupTime) {
        this.hangupTime = hangupTime;
    }

    public void setRingLength(int ringLength) {
        this.ringLength = ringLength;
    }

    public void setIvrLength(int ivrLength) {
        this.ivrLength = ivrLength;
    }

    public void setQueueLength(int queueLength) {
        this.queueLength = queueLength;
    }

    public void setTalkLength(Integer talkLength) {
        this.talkLength = talkLength;
    }

    public void setRecord(String record) {
        this.record = record;
    }

    public void setSatisfaction(Integer satisfaction) {
        this.satisfaction = satisfaction;
    }

    public void setExtensionNum(int extensionNum) {
        this.extensionNum = extensionNum;
    }

    public void setTrunkNum(String trunkNum) {
        this.trunkNum = trunkNum;
    }

    public void setCustomerId(String customerId) {
        this.customerId = customerId;
    }

    public void setCustomerPhone(String customerPhone) {
        this.customerPhone = customerPhone;
    }

    public void setCustomerCity(String customerCity) {
        this.customerCity = customerCity;
    }

    public void setGroupNum(int groupNum) {
        this.groupNum = groupNum;
    }

    public void setQueueTime(Date queueTime) {
        this.queueTime = queueTime;
    }

    public void setRingTime(Date ringTime) {
        this.ringTime = ringTime;
    }

    public void setCustomerProvince(String customerProvince) {
        this.customerProvince = customerProvince;
    }

    public void setCallTimeStart(String callTimeStart) {
        this.callTimeStart = callTimeStart;
    }

    public void setTalkLengthStart(String talkLengthStart) {
        this.talkLengthStart = talkLengthStart;
    }

    public void setCallTimeEnd(String callTimeEnd) {
        this.callTimeEnd = callTimeEnd;
    }

    public void setTalkLengthEnd(String talkLengthEnd) {
        this.talkLengthEnd = talkLengthEnd;
    }

    public void setCallTimeText(String callTimeText) {
        this.callTimeText = callTimeText;
    }

    public void setHangupTimeText(String hangupTimeText) {
        this.hangupTimeText = hangupTimeText;
    }

    public String getProvince() {
        return province;
    }

    public void setProvince(String province) {
        this.province = province;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public Date getHandleTime() {
        return handleTime;
    }

    public void setHandleTime(Date handleTime) {
        this.handleTime = handleTime;
    }

    public Integer getHandleStatus() {
        return handleStatus;
    }

    public void setHandleStatus(Integer handleStatus) {
        this.handleStatus = handleStatus;
    }

    public String getHandleTimeText() {
        if (this.handleTime == null){
            return "";
        }else {
            return DateUtil.convert(this.handleTime,"yyyy-MM-dd HH:mm:ss");
        }

    }
    public void setHandleTimeText(String handleTimeText) {
        this.handleTimeText = handleTimeText;
    }

    public String getSatisfactionText() {
       if (satisfaction == null || satisfaction == -1){
           return "未評價";
       }else if(satisfaction==0){
           return "不滿意";
       }else{
           return "滿意";
       }
    }

    public void setSatisfactionText(String satisfactionText) {
        this.satisfactionText = satisfactionText;
    }

    public String getHandleStatusText() {
        if (satisfaction == null || satisfaction == 0){
            return "未處理";
        }else if (satisfaction == 1){
            return "已處理";
        }else {
            return "未處理";
        }
    }

    public void setHandleStatusText(String handleStatusText) {
        this.handleStatusText = handleStatusText;
    }

    @Override
    public String toString() {
        return "CallRecord{" +
        ", callId=" + callId +
        ", userName=" + userName +
        ", callType=" + callType +
        ", fromNum=" + fromNum +
        ", toNum=" + toNum +
        ", callTime=" + callTime +
        ", ivrTime=" + ivrTime +
        ", answeredTime=" + answeredTime +
        ", hangupTime=" + hangupTime +
        ", ringLength=" + ringLength +
        ", ivrLength=" + ivrLength +
        ", queueLength=" + queueLength +
        ", talkLength=" + talkLength +
        ", record=" + record +
        ", satisfaction=" + satisfaction +
        ", extensionNum=" + extensionNum +
        ", trunkNum=" + trunkNum +
        ", customerId=" + customerId +
        ", customerPhone=" + customerPhone +
        ", customerCity=" + customerCity +
        "}";
    }
}

4、工具類

package com.ps.uzkefu.util;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.ps.uzkefu.apps.callcenter.entity.CallRecord;
import net.sf.jxls.transformer.XLSTransformer;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;

/**
 * Excel模板匯出工具類
 *
 * @author 
[email protected]
* @since 2015-4-16 */ @Component public class ExcelTemplateExportUtil { static Log log = LogFactory.getLog(ExcelTemplateExportUtil.class); /** * 生成匯出的Excel檔案,並返回匯出Excel檔案的輸入流 * 生成的Excel檔案是Excel 2003版本的 * * @param tmpFilePath 臨時檔案儲存路徑 * @param templateFilePath 匯出模版的路徑地址,例如:/WEB-INF/page/export/***.xls * @param dataList 要匯出的資料列表 * @param fileName 檔名稱 */ public static void export(HttpServletRequest request, HttpServletResponse response, String tmpFilePath, String templateFilePath, List<?> dataList,String fileName) { Assert.hasLength(templateFilePath, "Template file path is empty while get export excel file input stream !"); Assert.notNull(dataList, "Data list is empty while get export excel file input stream !"); Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap.put("dataList", dataList); XLSTransformer transformer = new XLSTransformer(); try { String tempFilePath = tmpFilePath +"/"+ UUIDUtil.genUUID() + ".xls"; templateFilePath = ClassUtils.getDefaultClassLoader().getResource("").getPath() + templateFilePath; transformer.transformXLS(templateFilePath, paramMap, tempFilePath); FileInputStream inputStream = new FileInputStream(tempFilePath); response.setContentType("application/vnd.ms-excel"); response.setHeader("Content-Disposition", "attachment;filename="+ new String(fileName.getBytes(),"ISO8859-1")); OutputStream outputStream = response.getOutputStream(); int ch; while ((ch = inputStream.read()) != -1) { outputStream.write(ch); } outputStream.flush(); outputStream.close(); } catch (Exception e) { log.error("Exception occurred while get export excel file input stream !", e); } } /** * * @param list 匯出的資料 * @param title excel檔案內容的標題 * @param sheetName sheet 名稱 * @param pojoClass 對應的實體類 * @param fileName 檔名 包含字尾名 * @param isCreateHeader * @param response 響應物件 用於下載 */ 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); } 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)); } public static void exportExcel(List<Map<String, Object>> list, String fileName, HttpServletResponse response){ defaultExport(list, fileName, response); } 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); } /** * 匯出操作 * @param fileName * @param response * @param workbook */ 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) { e.printStackTrace(); } } private static void defaultExport(List<Map<String, Object>> list, String fileName, HttpServletResponse response) { Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF); if (workbook != null); downLoadExcel(fileName, response, workbook); } /** * * @param filePath 檔案路徑 * @param titleRows 標題所佔行數 * @param headerRows 檔案頭所佔行數 * @param pojoClass 實體類 * @param <T> * @return */ public static <T> List<T> importExcel(String filePath,Integer titleRows,Integer headerRows, Class<T> pojoClass){ if (StringUtils.isBlank(filePath)){ return null; } ImportParams params = new ImportParams(); params.setTitleRows(titleRows); params.setHeadRows(headerRows); List<T> list = null; try { list = ExcelImportUtil.importExcel(new File(filePath), pojoClass, params); }catch (NoSuchElementException e){ e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return list; } public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass){ if (file == null){ return null; } ImportParams params = new ImportParams(); params.setTitleRows(titleRows); params.setHeadRows(headerRows); List<T> list = null; try { list = ExcelImportUtil.importExcel(file.getInputStream(), pojoClass, params); }catch (NoSuchElementException e){ e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return list; } public static void main(String args[]) { String filePath = "C:\\Users\\Admin\\Downloads\\呼入明細20180707133344.xls"; //解析excel, List<CallRecord> list = importExcel(filePath,0,1,CallRecord.class); //也可以使用MultipartFile,使用 FileUtil.importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass)匯入 for (CallRecord record:list ) { System.out.println(record); } System.out.println("匯入資料一共【"+list.size()+"】行"); } }

5、匯入的檔案

2.5 Map匯入,自由發揮

這天,老師把路飛叫到辦公室,總是被叫,能者的悲哀啊,讓他臨時匯入一批資料,到資料庫,但是中間需要處理一些欄位邏輯沒辦法直接匯入到資料庫, 這時路飛首先想到構造一個bean然後標記註解,匯入處理物件,但是想想一次的物件太過於浪費,不如用map試試,獲取map處理map也是一樣的 匯入的邏輯就變成了

        ImportParams params = new ImportParams();
        long start = new Date().getTime();
        List<Map<String, Object>> list = ExcelImportUtil.importExcel(
            new File(PoiPublicUtil.getWebRootPath("import/check.xls")), Map.class, params);

匯入後,處理每個map,然後入庫完美的解決了老師的需求,簡單更快捷,和bean匯入基礎沒有區別,省去了bean的構造時間