栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

新手也能使用EasyPoi导入导出Excel!!!

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

新手也能使用EasyPoi导入导出Excel!!!

EasyPOI的基本使用 使用EasyPoi导入导出Excel!!!

简介#
  • 本篇讲述EasyPOI的最基本使用,即导出和导入Excel文档。

关于概念#
  • 关于EasyPOI的概念不再累赘,我们需要知道的所有东西就是,它可以帮助我们把集合对象pojo转换为表格Excel。
  • 本章采用的是客户端上传和下载Excel文档作为范例,这也是最为频繁的使用场景或需求。

主要步骤#
  • 数据库表结构与Excel表结构是一致的,对于导入的情况,EasyPOI所需要做的事情就读取表格,将表格转为pojo的集合类对象,之后调用Service层中的方法写入数据库即可。
  • 对于导出的情况,则是先从Service层中读取数据,之后通过EasyPOI写出到文件即可。
  • 相对于导出操作而言,导入操作的要求实际上会更为严苛,其中涉及到数据合法性问题。
  • 务必使用JSR-303或其实现Hibernate Validator中的注解,来校验导入数据的合法性。否则写入数据库的数据可能会出现各种问题,本文不会对校验数据合法性进行测试。

1. 导入依赖


    cn.afterturn
    easypoi-base
    3.0.3


    cn.afterturn
    easypoi-web
    3.0.3


    cn.afterturn
    easypoi-annotation
    3.0.3

2. cv工具类

package com.greatpointcloud.enterprise.common.util.excel;

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.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.NoSuchElementException;
import java.io.File;
import java.net.URLEncoder;
import java.util.Map;


public class EasypoiUtil {

 
 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) {
        ExportParams exportParams = new ExportParams(title, sheetName);
 defaultExport(list, pojoClass, fileName, response, exportParams);
    }
    public static void exportExcel(List> list, String fileName, HttpServletResponse response) throws Exception {
 defaultExport(list, fileName, response);
    }
    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) {
 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;
    }
}

3. cv自定义注解

package com.greatpointcloud.enterprise.common.util.excel;

import java.lang.annotation.documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;


@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@documented
public @interface ExcelColumn {
    
    String value() default "";

    
    int col() default 0;
}

3. 编写自己所需要的pojo    注意这里无参构造一定要有 不然报错! 

package com.greatpointcloud.enterprise.common.util.excel;

import cn.afterturn.easypoi.excel.annotation.Excel;
import cn.afterturn.easypoi.excel.annotation.ExcelCollection;
import com.greatpointcloud.enterprise.erp.domain.ErpCommodityInfoExtend;

import java.io.Serializable;
import java.util.Date;
import java.util.List;


@Data

public class ExcelCommodifyInfo implements Serializable {
    @Excel(name = "分类Id", orderNum = "0")
    private Integer commodityCategoryId;
    @Excel(name = "商品名称", orderNum = "1")
    private String name;
    @Excel(name = "规格", orderNum = "2")
    private String standard;
    @Excel(name = "型号", orderNum = "3")
    private String model;
    @Excel(name = "颜色", orderNum = "4")
    private String color;
    @Excel(name = "仓库Id", orderNum = "5")
    private String warehouseId;
    @Excel(name = "供应商Id", orderNum = "6")
    private Integer supplierId;
    @ExcelCollection(name = "商品信息",orderNum = "7")
    private List erpCommodityInfoExtendList;
       
 // 无参构造一定要有 不然报错! 
public ExcelCommodifyInfo() {
}
}

4. 编写controller层

4.1  导出

@RequestMapping(value = "/erp/commodify/exportExcel", method = RequestMethod.GET)
public void exportExcel(HttpServletRequest request,HttpServletResponse response) {
    JSonObject user = (JSONObject) request.getAttribute(AuthTokenKey.USER);
    Integer orgInfoId = user.getInteger(AuthTokenKey.ORG_INFO_ID);
    List erpCommodifyInfoVOList = getErpCommodifyInfoVOList(new GetCommodityListQuery(), orgInfoId);
    List excelCommodifyInfos = JsonBeanCopyUtil.transformList(ExcelCommodifyInfo.class, erpCommodifyInfoVOList);
  
    EasypoiUtil.exportExcel(excelCommodifyInfos, "仓库商品表.xls", "仓库商品表", ExcelCommodifyInfo.class, "", response);
}

4.2 导入

@RequestMapping(value = "/erp/commodify/importExcel", method = RequestMethod.POST)
public List importExcel(@RequestParam(value="uploadFile", required = false) MultipartFile file) throws Exception {
    List excelCommodifyInfoExtends = EasypoiUtil.importExcel(file, 0,1,ExcelCommodifyInfoExtend.class);
    System.out.println(excelCommodifyInfoExtends.size());
    excelCommodifyInfoExtends.forEach(
            ExcelCommodifyInfoExtend -> System.out.println(ExcelCommodifyInfoExtend.toString())
    );
    return excelCommodifyInfoExtends;
}

postman可以这样上传和下载文件

 

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/322593.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号