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 WuZhiWei@HF
 * @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、导入的文件



猜你喜欢

转载自blog.csdn.net/zsj777/article/details/80951610
今日推荐