Excel简单的导入导出

文章介绍了在企业中常用的Excel导入导出功能,通过ApachePOI库和EasyPOI工具,简化了Java程序与Excel文档之间的数据交互。重点讲解了EasyPOI的使用,包括关键注解如@Excel、@ExcelCollection等,以及如何通过工具类实现数据的导出和导入操作。并提供了具体的代码示例,展示如何在实际业务场景中应用这些技术。
摘要由CSDN通过智能技术生成

导入:将文档中数据导入到内存中,后续可以添加到数据库

导出:将内存中的数据或数据库中查询的数据导出到文档中

注意:这里指的文档通常指的是基本的办公软件:word,excel,ppt

绝大多数公司都在使用word和excel,如果我们开发的系统支持导入导出,我们开发的软件就相对会有优势

1. 业务场景

案例1:
    公司举行活动时的签到表
        由系统运营人员将公司所有在职员工的信息导出为excel
        由公司后勤或行政人员对excel表进行修改,然后打印进行签到
案例2:
    采购清单
        后勤人员录入信息到excel
        系统维护人员将excel导入到数据库
    业务员线下推广收集用户数据,后面集中批量添加到数据库

2. POI的使用

咱们这里直接学习poi的使用,poi针对offices03(xls)07(xlsx)是单独写了相应的实现api,我们这里直接使用07版的处理方案(注:网上是有相应的兼容方案,可判断)

正在上传…重新上传取消

学习poi,面向度娘编程,随便找一篇文章,一看就会。引用文章:EasyPOI 详细教程以及注解的使用_easypoi-annotation_liaozuheng的博客-CSDN博客

3. EasyPOI导出数据

为了提高开发效率,我们这里使用easyPOI进行数据的导入导出

easypoi导入/导出excel其实就是domain对象属性和excel列的映射,而easypoi是通过注解的方式来做映射的,我们学习easypoi其实就是学会使用工具类和掌握它的常用注解

@Excel 作用到filed上面,是对Excel一列的一个描述
@ExcelCollection 表示一个集合,主要针对一对多的导出,比如一个老师对应多个科目,科目就可以用集合表示
@ExcelEntity 表示一个继续深入导出的实体,但他没有太多的实际意义,只是告诉系统这个对象里面同样有导出的字段

@ExcelIgnore 和名字一样表示这个字段被忽略跳过这个导导出
@ExcelTarget 这个是作用于最外层的对象,描述这个对象的id,以便支持一个对象可以针对不同导出做出不同处理
3.1导包
<dependency>
    <groupId>cn.afterturn</groupId>
    <artifactId>easypoi-base</artifactId>
    <version>4.2.0</version>
</dependency>
<dependency>
    <groupId>cn.afterturn</groupId>
    <artifactId>easypoi-web</artifactId>
    <version>4.2.0</version>
</dependency>
<dependency>
    <groupId>cn.afterturn</groupId>
    <artifactId>easypoi-annotation</artifactId>
    <version>4.2.0</version>
</dependency>
3.2添加工具类
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.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.multipart.MultipartFile;

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

/**
 * Excel导入导出工具类
 * @author hm
 */
public class ExcelUtils{

    /**
     * 导出工具类
     * @param list
     * @param title
     * @param sheetName
     * @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);
    }

    /**
     * 导出工具类
     * @param list
     * @param title
     * @param sheetName
     * @param pojoClass
     * @param fileName
     * @param response
     */
    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);
    }

    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) {
            //throw new NormalException(e.getMessage());
        }
    }

    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);
    }

    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){
            //throw new NormalException("模板不能为空");
        } catch (Exception e) {
            e.printStackTrace();
            //throw new NormalException(e.getMessage());
        } 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){
            // throw new NormalException("excel文件不能为空");
        } catch (Exception e) {
            //throw new NormalException(e.getMessage());
            System.out.println(e.getMessage());
        }
        return list;
    }
}
3.3前端请求导出数据
<el-form-item>
          <el-button type="warning" @click="exportData">导出</el-button>
</el-form-item>
exportData(){
    location.href="http://localhost:8080/location/exportExcel";
}
3.4在实体类上打上注解


public class Location implements Serializable {

      /**
       *  区域id
       * */
      @Excel(name="区域id",orderNum = "1" , width=30)
      private  String  qyId;
      /**
      *  区域名称
      * */
      @Excel(name="区域名称",orderNum = "2" , width=30)
      private  String  qyName;
      /**
      *  父级id
      * */
      @Excel(name="父级id",orderNum = "3" , width=30)
      private  String  qyPid;
      /**
      *  设备安放状态
     * */
      @Excel(name="区域设备状态",orderNum = "4" , width=30)
      private  Integer  qyType;
      /**
      *   操作人姓名
      * */
      @Excel(name="操作人姓名",orderNum = "5" , width=30)
      private  String  operatorName;
      /**
       *  区域的全名
       * */
      @Excel(name="区域全名",orderNum = "6" , width=30)
      private String qyAllName;


}
3.5后台提供导出接口
    @GetMapping("/exportExcel")
    public Result export( HttpServletResponse response){
        try {
            List<Location >locations = locationService.getAll();
            ExcelUtils.exportExcel(locations, null, "区域信息", Location.class, "Location.xlsx", response);
           return Result.succeed("文件导出成功");
        } catch (Exception e) {
            e.printStackTrace();
           return Result.fail(500,"文件导出失败");
        }
    }

4文件导入数据

4.1前端代码
<el-form-item>
     <!-- 默认name="file" -->
     <el-upload class="upload-demo"
         action="http://localhost:8080/location/importExcel"
         list-type="text">
      <el-button type="danger">导入</el-button>
   </el-upload>
</el-form-item>
4.2后台代码
    /**
     *   Excel表的导入
     * */
    @PostMapping("/importExcel")
    public Result importExcel(@RequestPart("file") MultipartFile file){//前端默认传来的是文件 
    file
        try {
            List<Location> list= ExcelUtils.importExcel(file,0,1,Location.class);
            System.out.println("导入数据一共【"+list.size()+"】行");
             //导入之后可以调用数据库代码来实现添加功能
            return Result.succeed(list);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail(500,"Excel表导入失败");
        }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值