java使用EasyExcel完成excel的导入导出实例

官网地址:https://easyexcel.opensource.alibaba.com/

Excel导入:

java使用EasyExcel完成excel的导入导出实例_第1张图片
Controller:

@ApiOperation("测试导入")
@PostMapping(value = "/import")
public void importLiveAdvanceNoticeData(@RequestParam("file") MultipartFile file) {
	testService.importData(file);
}

service省略…
serviceImpl:

@Override
public void importData(MultipartFile file) {
	try {
		//			   文件流				  导入的excel对应实体类				自己写的监听器				   监听器中注入的mapper,对数据库操作	
		EasyExcel.read(file.getInputStream(), DtLiveAdvanceNoticeImportVO.class, new LiveAdvanceNoticeListener(dtLiveAdvanceNoticeMapper, dtChannelLiveConfDao)).sheet().doRead();
	} catch (IOException e) {
		e.printStackTrace();
	}
}

VO:

@Data
@ApiModel("导入VO")
public class DtLiveAdvanceNoticeImportVO implements Serializable {


    @ExcelProperty(value = "test")
    private String test;
}

监听器:

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Slf4j
public class LiveAdvanceNoticeListener implements ReadListener<DtLiveAdvanceNoticeImportVO> {

    Set<String> errMsg = new HashSet<>();

    /**
     * 每隔5条存储数据库,实际使用中可以100条,然后清理list ,方便内存回收
     */
    private static final int BATCH_COUNT = 100;
    /**
     * 缓存的数据
     */
    private List<DtLiveAdvanceNoticeImportVO> liveAdvanceNoticeVOList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
    /**
     * 假设这个是一个DAO,当然有业务逻辑这个也可以是一个service。当然如果不用存储这个对象没用。
     */
    private DtLiveAdvanceNoticeMapper dtLiveAdvanceNoticeMapper;
    private DtChannelLiveConfDao dtChannelLiveConfDao;

    /**
     * 如果使用了spring,请使用这个构造方法。每次创建Listener的时候需要把spring管理的类传进来
     */
    public LiveAdvanceNoticeListener(DtLiveAdvanceNoticeMapper dtLiveAdvanceNoticeMapper, DtChannelLiveConfDao dtChannelLiveConfDao) {
        this.dtLiveAdvanceNoticeMapper = dtLiveAdvanceNoticeMapper;
        this.dtChannelLiveConfDao = dtChannelLiveConfDao;
    }

    /**
     * 这个每一条数据解析都会来调用
     *
     * @param data    one row value. Is is same as {@link AnalysisContext#readRowHolder()}
     * @param context
     */
    @Override
    public void invoke(DtLiveAdvanceNoticeImportVO data, AnalysisContext context) {
        log.info("解析到一条数据:{}", JSON.toJSONString(data));
            liveAdvanceNoticeVOList.add(data);
            // 达到BATCH_COUNT了,需要去存储一次数据库,防止数据几万条数据在内存,容易OOM
            if (liveAdvanceNoticeVOList.size() >= BATCH_COUNT) {
                saveData();
                // 存储完成清理 list
                liveAdvanceNoticeVOList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
            }
    }

    /**
     * 所有数据解析完成了 都会来调用
     *
     * @param context
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // 这里也要保存数据,确保最后遗留的数据也存储到数据库
        saveData();
        log.info("所有数据解析完成!");
    }

    /**
     * 加上存储数据库
     */
    private void saveData() {
        log.info("{}条数据,开始存储数据库!", cachedDataList.size());
		//这里是对数据库的操作,demoDao换成自己在service中注入的mapper或者dao
        demoDAO.save(cachedDataList);
        log.info("存储数据库成功!");
    }

}

导出

Controller:

@ApiOperation("测试excel导出")
    @PostMapping("excelExport")
    public void excelExport(@RequestBody TestDTO dto) throws IOException {
    	//需要导出的集合数据
        List<TestVO> list = TestService.excelExport(dto, request);
        //设置文件名
        Export.setExcelRespProp(response, "excel名称");
        //写数据
        EasyExcel.write(response.getOutputStream())
        	//导出的VO数据来源
            .head(TestVO.class)
            //导出文件的后缀,.csv  .xls    .xlsx .....
            .excelType(ExcelTypeEnum.XLSX)
            .sheet("sheet名称")
            .doWrite(list);

Export:

import java.net.URLEncoder;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
public class Export {
    public static void setCsvRespProp(HttpServletResponse response, String filename) throws UnsupportedEncodingException {
        response.setContentType("text/csv");
        response.setCharacterEncoding("utf-8");
        String newFile = URLEncoder.encode(filename, "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + newFile + ".csv");
    }

    public static void setExcelRespProp(HttpServletResponse response, String filename) throws UnsupportedEncodingException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String newFile = URLEncoder.encode(filename, "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "filename*=utf-8''" + newFile + ".xlsx");
    }

}

VO:导出对应的实体类

@Data
@ApiModel("test导出VO")
public class TestVO{

    @ApiModelProperty("test")
    @ExcelProperty(value = "test")
    @ColumnWidth(20)//设置宽度
    private String operationDep;
	
	
	}

你可能感兴趣的:(Util,java,excel)