欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Java使用EasyExcel實現(xiàn)Excel的導入導出

 更新時間:2023年07月31日 09:20:28   作者:鑄鍵為犁  
這篇文章主要給大家介紹了關于Java使用EasyExcel實現(xiàn)Excel的導入導出,在各種系統(tǒng)中,導入導出的數(shù)據(jù)一般都是通過Excel來完成的,需要的朋友可以參考下

前言

在真實的開發(fā)者場景中,經(jīng)常會使用excel作為數(shù)據(jù)的載體,進行數(shù)據(jù)導入和導出的操作,使用excel的導入和導出有很多種解決方案,本篇記錄一下EasyExcel的使用。

一、EasyExcel是什么?

EasyExcel是一個開源的項目,是阿里開發(fā)的。EasyExcel可以簡化Excel表格的導入和導出操作,使用起來簡單快捷,易上手。

二、使用步驟

1.導入依賴

在pom.xml中導入我們需要使用的依賴

 <!--文件上傳-->
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.4</version>
    </dependency>
     <!-- easy excel依賴 -->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>easyexcel</artifactId>
      <version>2.1.6</version>
    </dependency>

2.編寫文件上傳配置

在springMVC配置文件中添加如下配置

<!--    文件上傳配置-->
    <bean id="multipartResolver"  class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 請求的編碼格式,必須和jSP的pageEncoding屬性一致,以便正確讀取表單的內(nèi)容,默認為ISO-8859-1 -->
        <property name="defaultEncoding" value="utf-8"/>
        <!-- 上傳文件大小上限,單位為字節(jié)(10485760=10M) -->
        <property name="maxUploadSize" value="10485760"/>
    </bean>

3.配置表頭對應實體類

package com.lzl.entityBo;

import com.alibaba.excel.annotation.ExcelIgnore;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.format.DateTimeFormat;

/**
 * --效率,是成功的核心關鍵--
 *
 * @Author lzl
 * @Date 2022/10/29 13:59
 */

public class EmployeeBo {
    @ExcelProperty(value = "工號")//表頭注解
    private Integer emp_no;
    @ExcelProperty(value = "姓名")
    private String emp_name;
    @ExcelProperty(value = "性別")
    private String  emp_gender;
    @ExcelProperty(value = "年齡")
    private Integer emp_age;
    @ExcelIgnore//不輸出該列
    private Integer emp_dept_no;
    @ExcelProperty(value = "薪資")
    private Double emp_salary;
    @ExcelProperty(value = "入職時間")
    @DateTimeFormat("yyyy-MM-dd")//格式化日期時間
    private String emp_hire_time;
    @ExcelProperty(value = "職位")
    private String emp_position;
    @ExcelProperty(value = "狀態(tài)")
    private Integer emp_status;

    public EmployeeBo() {
    }

    public EmployeeBo(Integer emp_no, String emp_name, String emp_gender, Integer emp_age, Integer emp_dept_no, Double emp_salary, String emp_hire_time, String emp_position, Integer emp_status) {
        this.emp_no = emp_no;
        this.emp_name = emp_name;
        this.emp_gender = emp_gender;
        this.emp_age = emp_age;
        this.emp_dept_no = emp_dept_no;
        this.emp_salary = emp_salary;
        this.emp_hire_time = emp_hire_time;
        this.emp_position = emp_position;
        this.emp_status = emp_status;
    }

    public Integer getEmp_no() {
        return emp_no;
    }

    public void setEmp_no(Integer emp_no) {
        this.emp_no = emp_no;
    }

    public String getEmp_name() {
        return emp_name;
    }

    public void setEmp_name(String emp_name) {
        this.emp_name = emp_name;
    }

    public String getEmp_gender() {
        return emp_gender;
    }

    public void setEmp_gender(String emp_gender) {
        this.emp_gender = emp_gender;
    }

    public Integer getEmp_age() {
        return emp_age;
    }

    public void setEmp_age(Integer emp_age) {
        this.emp_age = emp_age;
    }

    public Integer getEmp_dept_no() {
        return emp_dept_no;
    }

    public void setEmp_dept_no(Integer emp_dept_no) {
        this.emp_dept_no = emp_dept_no;
    }

    public Double getEmp_salary() {
        return emp_salary;
    }

    public void setEmp_salary(Double emp_salary) {
        this.emp_salary = emp_salary;
    }

    public String getEmp_hire_time() {
        return emp_hire_time;
    }

    public void setEmp_hire_time(String emp_hire_time) {
        this.emp_hire_time = emp_hire_time;
    }

    public String getEmp_position() {
        return emp_position;
    }

    public void setEmp_position(String emp_position) {
        this.emp_position = emp_position;
    }

    public Integer getEmp_status() {
        return emp_status;
    }

    public void setEmp_status(Integer emp_status) {
        this.emp_status = emp_status;
    }

    @Override
    public String toString() {
        return "EmployeeBo{" +
                "emp_no=" + emp_no +
                ", emp_name='" + emp_name + '\'' +
                ", emp_gender='" + emp_gender + '\'' +
                ", emp_age=" + emp_age +
                ", emp_dept_no=" + emp_dept_no +
                ", emp_salary=" + emp_salary +
                ", emp_hire_time='" + emp_hire_time + '\'' +
                ", emp_position='" + emp_position + '\'' +
                ", emp_status=" + emp_status +
                '}';
    }
}

4.監(jiān)聽器編寫

使用EasyExcel需要進行全局監(jiān)聽配置新建一個listener包,并在該包下新建一個MyListener類,繼承AnalysisEventListener類,泛型設置為當前需要導出的類,我這里需要導出的是員工數(shù)據(jù),因此我將泛型設置為員工類,整體代碼如下:

package com.lzl.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.lzl.entity.Employee;
import com.lzl.entityBo.EmployeeBo;
import com.lzl.service.EmployeeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

//easy excel 監(jiān)聽器
@Component
@Scope("prototype")//標記此處的監(jiān)聽器為多例的,防止并發(fā)讀操作時出現(xiàn)錯誤
public class EmployeeReadListener extends AnalysisEventListener<EmployeeBo> {

    //此處自動注入業(yè)務層的新增功能
    @Autowired
    private EmployeeService service;

    @Override
    public void invoke(EmployeeBo data, AnalysisContext analysisContext) {
        //每讀取一行數(shù)據(jù)都會調(diào)用一次,會把每一行數(shù)據(jù)封裝到employee
        //屬性不一致時,使用屬性拷貝
        Employee employee = new Employee();
        BeanUtils.copyProperties(data,employee);
        service.addNewEmployee(employee);//調(diào)用新增方法
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        //所有數(shù)據(jù)解析完畢執(zhí)行該方法
    }
}

此處監(jiān)聽器的作用是,當我們每次從excel表格中讀取一行數(shù)據(jù)時,我們都需要進行新增操作,而新增操作交給我們的監(jiān)聽器去完成。

5.控制層

控制層負責接收前端傳過來的文件流,然后使用EasyExcel來對導入或者導出的數(shù)據(jù)進行進一步的處理,并把處理結(jié)果返回,需要注意的是,對于導出操作,該方法并沒有返回值,因此我們不需要返回值,而對于導入方法,此處我使用的是layui的前端,所以返回的數(shù)據(jù)格式是layui可以接收的工具類。

package com.lzl.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.builder.ExcelReaderBuilder;
import com.alibaba.excel.read.builder.ExcelReaderSheetBuilder;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.builder.ExcelWriterSheetBuilder;
import com.lzl.entityBo.EmployeeBo;
import com.lzl.listener.EmployeeReadListener;
import com.lzl.service.EmployeeService;
import com.lzl.util.ResultLayUi;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import java.net.URLEncoder;
import java.util.List;

@Controller
@RequestMapping("/excel")
public class UploadExcelController {

    //注入監(jiān)聽器
    @Autowired
    private EmployeeReadListener listener;

    //注入業(yè)務層
    @Autowired
    private EmployeeService service;
    /**
     *
     * @param file 獲得前端上傳的文件  EasyExcel.read 需要傳入三個參數(shù) 文件流 操作實體類的字節(jié)碼 監(jiān)聽器
     * @return 0 成功上傳
     * @throws IOException
     */
    @RequestMapping("read")
    @ResponseBody
    public ResultLayUi<String> readExcel(MultipartFile file) throws IOException {
        // 得到excel讀取對象  //通過文件獲得流, 獲得讀取文件的class    填入監(jiān)聽器 監(jiān)聽器每讀取一行就執(zhí)行一次新增
        ExcelReaderBuilder read = EasyExcel.read(file.getInputStream(), EmployeeBo.class, listener);
        //獲取表格
        ExcelReaderSheetBuilder sheet = read.sheet();
        //讀取表格
        sheet.doRead();
        ResultLayUi<String> resultLayUi = new ResultLayUi<String>();
        resultLayUi.setCode(0);
        resultLayUi.setMsg("已成功導入");
        return resultLayUi;
    }
    @RequestMapping("write")
    public void writeExcel(String nos,HttpServletResponse response) throws IOException {
        //設置響應頭
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        //導出的文件名
        String filename = URLEncoder.encode("員工信息","utf-8");
        //設置響應頭
        response.setHeader("Content-Disposition","attachment;filename="+filename+".xlsx");
        //獲得流對象
        ServletOutputStream outputStream = response.getOutputStream();
        //獲得write對象
        ExcelWriterBuilder write = EasyExcel.write(outputStream, EmployeeBo.class);
        //獲得數(shù)據(jù)表對象
        ExcelWriterSheetBuilder sheet = write.sheet();
        //準備需要輸出的數(shù)據(jù)   調(diào)用業(yè)務層,獲得所有需要導出的數(shù)據(jù)
        List<EmployeeBo> list = service.getExcelDataByNos(nos);
        //生成表格文件
        sheet.doWrite(list);
    }
}

6.前端代碼

前端使用的是layui的文件上傳組件。所有相關代碼如下:

下載:這里我使用了switch-case分支來對多個按鈕的事件進行區(qū)分和綁定,layui的組件加載:

  layui.use(['table', 'layer', 'form', 'laydate', 'transfer','upload','element'], function () {
      var table = layui.table;
      var layer = layui.layer;
      var form = layui.form;
      var laydate = layui.laydate;
      var transfer = layui.transfer;
      var upload = layui.upload;
      var element = layui.element;
      var $ = layui.$;

按鈕:

  	  <button class="layui-btn layui-btn-xs layui-btn-normal"  lay-event="write">
        <i class="layui-icon">&#xe67d;</i>導出數(shù)據(jù)
      </button>
      <button class="layui-btn layui-btn-xs layui-btn-normal"  lay-event="read">
        <i class="layui-icon">&#xe613;</i>導入數(shù)據(jù)
      </button>

上傳彈出層:

 <!-- 上傳excel表格 區(qū)域-->
  <div class="layui-form-item" id="import" style="display:none;">
    <form class="layui-form" onsubmit="return false;" id="readExcel">
      <div class="layui-form-item">
        <label class="layui-form-label"></label>
        <div class="layui-input-block">
          <div class="layui-upload">
            <button type="button" class="layui-btn" id="test1">上傳文件</button>
            <div style="width: 95px;">
              <div class="layui-progress layui-progress-big" lay-showpercent="yes" lay-filter="demo">
                <div class="layui-progress-bar" lay-percent=""></div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </form>
  </div>
 case 'write':
            if (data.length === 0) {
              layer.msg('請至少選擇一行');
            } else if (data.length > 1) {
              $list = checkStatus.data;
              $ids = [];
              for (var i = 0; i < $list.length; i++) {
                $ids[i] = $list[i].emp_no;
              }
              $strIds = ""
              for (var i = 0; i < $ids.length; i++) {
                $strIds += $ids[i] + ",";
              }
              layer.confirm("確認導出所有選中行嗎?", function (index) {
                window.location.href = "http://localhost:8080/excel/write?nos=" + $strIds;
                layer.close(index);
              });
            }
            break;
case 'read':
          layer.open({
            type: 1,
            title: '上傳excel文件',
            area: ['300px', '300px'],
            content: $('#import')
            //這里content是一個DOM,注意:最好該元素要存放在body最外層,否則可能被其它的相對元素所影響
          });
            break;
		//上傳文件的事件:
      //常規(guī)使用 - excel表格上傳
     upload.render({
        elem: '#test1'
        ,accept: 'file' //普通文件
        ,exts: 'xlsx' //上傳文件格式
        , url: 'http://localhost:8080/excel/read' 
        , done: function (res) {
          console.log(res);
          //如果上傳失敗
          if (res.code > 0) {
            layer.msg('上傳失敗');
          } else {
            active.reload();
            layer.msg(res.msg, {
              icon: 6,
              time: 1500 //2秒關閉(如果不配置,默認是3秒)
            }, function () {
              //關閉彈出層
              layer.closeAll();
              element.progress('demo', '0%'); //進度條復位
            });
          }
        }
        //進度條
        , progress: function (n, elem, e) {
          element.progress('demo', n + '%'); //可配合 layui 進度條元素使用
          if (n == 100) {
            //layer.msg('上傳完畢', { icon: 1 });
          }
        }
      });

總結(jié)

EasyExcel是一個excel導入導出的解決方案,非常好用。

到此這篇關于Java使用EasyExcel實現(xiàn)Excel的導入導出的文章就介紹到這了,更多相關EasyExcel實現(xiàn)Excel導入導出內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

  • Java中的DelayQueue實現(xiàn)原理及應用場景詳解

    Java中的DelayQueue實現(xiàn)原理及應用場景詳解

    這篇文章主要介紹了Java中的DelayQueue實現(xiàn)原理及應用場景詳解,DelayQueue是一個沒有邊界BlockingQueue實現(xiàn),加入其中的元素必需實現(xiàn)Delayed接口,當生產(chǎn)者線程調(diào)用put之類的方法加入元素時,會觸發(fā)Delayed接口中的compareTo方法進行排序,需要的朋友可以參考下
    2023-12-12
  • Spring實現(xiàn)一個簡單的SpringIOC容器

    Spring實現(xiàn)一個簡單的SpringIOC容器

    本篇文章主要介紹了Spring實現(xiàn)一個簡單的SpringIOC容器,具有一定的參考價值,感興趣的小伙伴們可以參考一下。
    2017-04-04
  • Spring Boot2.0整合ES5實現(xiàn)文章內(nèi)容搜索實戰(zhàn)

    Spring Boot2.0整合ES5實現(xiàn)文章內(nèi)容搜索實戰(zhàn)

    這篇文章主要介紹了Spring Boot2.0整合ES5實現(xiàn)文章內(nèi)容搜索實戰(zhàn),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-01-01
  • SpringBoot+Redis使用AOP防止重復提交的實現(xiàn)

    SpringBoot+Redis使用AOP防止重復提交的實現(xiàn)

    本文主要介紹了SpringBoot+Redis使用AOP防止重復提交的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2023-07-07
  • 基于java實現(xiàn)一個脫敏組件

    基于java實現(xiàn)一個脫敏組件

    這篇文章主要為大家詳細介紹了如何基于java實現(xiàn)一個脫敏組件,文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起學習一下
    2024-11-11
  • Java Tree結(jié)構數(shù)據(jù)中查找匹配節(jié)點方式

    Java Tree結(jié)構數(shù)據(jù)中查找匹配節(jié)點方式

    這篇文章主要介紹了Java Tree結(jié)構數(shù)據(jù)中查找匹配節(jié)點方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-09-09
  • java 三種將list轉(zhuǎn)換為map的方法詳解

    java 三種將list轉(zhuǎn)換為map的方法詳解

    這篇文章主要介紹了java 三種將list轉(zhuǎn)換為map的方法詳解的相關資料,需要的朋友可以參考下
    2017-01-01
  • 詳解在spring中使用JdbcTemplate操作數(shù)據(jù)庫的幾種方式

    詳解在spring中使用JdbcTemplate操作數(shù)據(jù)庫的幾種方式

    這篇文章主要介紹了詳解在spring中使用JdbcTemplate操作數(shù)據(jù)庫的幾種方式,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2020-07-07
  • MybatisPlus,無XML分分鐘實現(xiàn)CRUD操作

    MybatisPlus,無XML分分鐘實現(xiàn)CRUD操作

    這篇文章主要介紹了MybatisPlus,無XML分分鐘實現(xiàn)CRUD操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-08-08
  • 詳解JAVA序列化及實際應用場景分析

    詳解JAVA序列化及實際應用場景分析

    序列化就是將對象轉(zhuǎn)換為可以存儲或傳輸?shù)男问?以實現(xiàn)對象持久化存儲到磁盤中,或者在網(wǎng)絡中傳輸,這篇文章介紹JAVA序列化及實際應用場景分析,感興趣的朋友跟隨小編一起看看吧
    2024-12-12

最新評論