sprinboot 使用easypoi实现文件导出Excel

在很多时候,我们需要将一些报表生成Excel的格式文件,相信这个都会有自己的一套util,在这里,简单实现以下:
做一笔记:
1.创建Excel po (注:里边字段为Excel中每列的列名和对于的数据,设置宽高,设置列的顺序(orderNum)等…)

@ExcelTarget("ResCSBZT01130023Po")
public class ResCSBZT01130023Po  implements Serializable {

    @Excel(name = "省",  isImportField = "true_st",height = 10, width = 15,needMerge = true,orderNum="1")
    private String  province;

    @Excel(name = "市", isImportField = "true_st",height = 10, width = 20,needMerge = true,orderNum="2")
    private String city;

    @Excel(name = "区",  isImportField = "true_st",height = 10, width = 15,needMerge = true,orderNum="3")
    private String  district;

    @Excel(name = "微信名", isImportField = "true_st",height = 10, width = 20,needMerge = true,orderNum="4")
    private String nickName;

    @Excel(name = "微信号", isImportField = "true_st",height = 10, width = 20,needMerge = true,orderNum="5")
    private String wxCode;


    @Excel(name = "Mac地址", isImportField = "true_st",height = 10, width = 20,needMerge = true,orderNum="6")
    private String mac;

    @Excel(name = "操作系统", isImportField = "true_st",height = 10, width = 20,needMerge = true,orderNum="7")
    private String os;

    @Excel(name = "手机设备号", isImportField = "true_st",height = 10, width = 20,needMerge = true,orderNum="6")
    private String phoneModel;

    @Excel(name = "采集软件版本", isImportField = "true_st",height = 10, width = 20,needMerge = true,orderNum="8")
    private String ddVer;

    @Excel(name = "微信版本", isImportField = "true_st",height = 10, width = 20,needMerge = true,orderNum="9")
    private String wxVer;


   // @Excel(name = "采集状态", isImportField = "true_st",height = 10, width = 20,needMerge = true,orderNum="6")
   // private String ddState;


    @Excel(name = "控制状态", isImportField = "true_st",height = 10, width = 20,needMerge = true,orderNum="10")
    private String msgState;


    @Excel(name = "最后消息接受时间", isImportField = "true_st",height = 10, width = 20,needMerge = true,orderNum="11")
    private String lastTime;


    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 String getDistrict() {
        return district;
    }

    public void setDistrict(String district) {
        this.district = district;
    }

    public String getNickName() {
        return nickName;
    }

    public void setNickName(String nickName) {
        this.nickName = nickName;
    }

    public String getWxCode() {
        return wxCode;
    }

    public void setWxCode(String wxCode) {
        this.wxCode = wxCode;
    }

    public String getMac() {
        return mac;
    }

    public void setMac(String mac) {
        this.mac = mac;
    }

    public String getOs() {
        return os;
    }

    public void setOs(String os) {
        this.os = os;
    }

    public String getPhoneModel() {
        return phoneModel;
    }

    public void setPhoneModel(String phoneModel) {
        this.phoneModel = phoneModel;
    }

    public String getDdVer() {
        return ddVer;
    }

    public void setDdVer(String ddVer) {
        this.ddVer = ddVer;
    }

    public String getWxVer() {
        return wxVer;
    }

    public void setWxVer(String wxVer) {
        this.wxVer = wxVer;
    }

    public String getMsgState() {
        return msgState;
    }

    public void setMsgState(String msgState) {
        this.msgState = msgState;
    }

    public String getLastTime() {
        return lastTime;
    }

    public void setLastTime(String lastTime) {
        this.lastTime = lastTime;
    }

    public ResCSBZT01130023Po(String province, String city, String district, String nickName, String wxCode, String mac, String os, String phoneModel, String ddVer, String wxVer, String msgState, String lastTime) {
        this.province = province;
        this.city = city;
        this.district = district;
        this.nickName = nickName;
        this.wxCode = wxCode;
        this.mac = mac;
        this.os = os;
        this.phoneModel = phoneModel;
        this.ddVer = ddVer;
        this.wxVer = wxVer;
        this.msgState = msgState;
        this.lastTime = lastTime;
    }

生成 Constructor和 get set方法
接下来就是需要去查你Excel中需要的数据了

2.对应数据(db中查找出需导出数据,遍历将数据扔到ExcelPo的集合里边)

  List salesExcelPoList =  new ArrayList<>();
   SalesPo salesPo = shopService.getSales(orderInfoPO);
   List salesList = salesPo.getSalesList();
   
  salesList.forEach(sales -> {
            String goodsName = sales.getGoodsName();
            BigDecimal goodsPrice = sales.getGoodsPrice();
            Integer goodsSalesNum = sales.getGoodsSalesNum();
            BigDecimal goodsSalesPrice = null;
            if (null != goodsSalesNum && goodsSalesNum>0){
                goodsSalesPrice =sales.getGoodsPrice().multiply(BigDecimal.valueOf(sales.getGoodsSalesNum()));
            }
            SalesExcelPo salesExcelPo = new SalesExcelPo(goodsName, goodsPrice, goodsSalesNum, goodsSalesPrice);
            salesExcelPoList.add(salesExcelPo);
        });
  1. 接下来就是去生成Excel了(一般直接用response导出就好,当然也可以生成InputStream流对数据进行其他发邮件,上传 下载等操作)
    我这里需要邮箱发送所以简单做一判断:
   //导出操作
        if (orderInfoPO.getEmail() == null){
            FileUtil.exportExcel(salesExcelPoList, "销售报表", "1", SalesExcelPo.class, "销售报表.xls", response);
        }else {
            InputStream inputStream=FileUtil.exportExcelEmail(salesExcelPoList, "销售报表", "1", SalesExcelPo.class, "销售报表.xls", response);
            utilService.sendMail("销售报表",orderInfoPO.getEmail(),"销售报表.xls",inputStream,from);
        }

FIleUtil工具类:

package com.kingstones.common.utils;

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 org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

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

@Component
public class FileUtil {
	public static void exportExcel(List list, String title, String sheetName, Class pojoClass, String fileName,
			boolean isCreateHeader, HttpServletResponse response) throws Exception {
		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 InputStream exportExcelEmail(List list, String title, String sheetName, Class pojoClass, String fileName,
								   HttpServletResponse response) {
		return defaultEmailExport(list, pojoClass, fileName, response, new ExportParams(title, sheetName));
	}

	public static void exportExcel(List> list, String fileName, HttpServletResponse response)
			throws Exception {
		defaultExport(list, fileName, response);
	}

	private  static InputStream defaultEmailExport(List list, Class pojoClass, String fileName, HttpServletResponse response,
									  ExportParams exportParams) {
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		InputStream inputStream = null;
		Workbook workbook = null;
		try {
			workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (workbook != null)
			try {
				workbook.write(outputStream);
				 inputStream= new ByteArrayInputStream(outputStream.toByteArray());
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return inputStream;
	}

	private static void defaultExport(List list, Class pojoClass, String fileName, HttpServletResponse response,
			ExportParams exportParams) {

		Workbook workbook = null;
		try {
			workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (workbook != null)
		try {
			downLoadExcel(fileName, response, workbook);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
 
	private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook)
			throws Exception {
		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) {
			throw new Exception(e.getMessage());
		}
	}
 
	private static void defaultExport(List> list, String fileName, HttpServletResponse response)
			throws Exception {
		Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF);
		if (workbook != null)
			;
		downLoadExcel(fileName, response, workbook);
	}
 
	public static  List importExcel(String filePath, Integer titleRows, Integer headerRows, Class pojoClass)
			throws Exception {
		if (org.apache.commons.lang3.StringUtils.isBlank(filePath)) {
			return null;
		}
		ImportParams params = new ImportParams();
		params.setTitleRows(titleRows);
		params.setHeadRows(headerRows);
		List list = null;
		try {
			list = ExcelImportUtil.importExcel(new File(filePath), pojoClass, params);
		} catch (NoSuchElementException e) {
			throw new Exception("模板不能为空");
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception(e.getMessage());
		}
		return list;
	}
 
	public static  List importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class pojoClass)
			throws Exception {
		if (file == null) {
			return null;
		}
		ImportParams params = new ImportParams();
		params.setTitleRows(titleRows);
		params.setHeadRows(headerRows);
		List list = null;
		try {
			list = ExcelImportUtil.importExcel(file.getInputStream(), pojoClass, params);
		} catch (NoSuchElementException e) {
			throw new Exception("excel文件不能为空");
		} catch (Exception e) {
			throw new Exception(e.getMessage());
		}
		return list;
	}
 
}

这样简单的Excel 工具就好了;

资料:https://blog.csdn.net/xufei512/article/details/82632266

你可能感兴趣的:(WorkBook,Excel,easyPoi)