亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Java使用EasyExcel實(shí)現(xiàn)Excel的導(dǎo)入導(dǎo)出

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

前言

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

一、EasyExcel是什么?

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

二、使用步驟

1.導(dǎo)入依賴

在pom.xml中導(dǎo)入我們需要使用的依賴

 <!--文件上傳-->
    <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">
        <!-- 請(qǐng)求的編碼格式,必須和jSP的pageEncoding屬性一致,以便正確讀取表單的內(nèi)容,默認(rèn)為ISO-8859-1 -->
        <property name="defaultEncoding" value="utf-8"/>
        <!-- 上傳文件大小上限,單位為字節(jié)(10485760=10M) -->
        <property name="maxUploadSize" value="10485760"/>
    </bean>

3.配置表頭對(duì)應(yīng)實(shí)體類

package com.lzl.entityBo;

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

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

public class EmployeeBo {
    @ExcelProperty(value = "工號(hào)")//表頭注解
    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 = "入職時(shí)間")
    @DateTimeFormat("yyyy-MM-dd")//格式化日期時(shí)間
    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需要進(jìn)行全局監(jiān)聽配置新建一個(gè)listener包,并在該包下新建一個(gè)MyListener類,繼承AnalysisEventListener類,泛型設(shè)置為當(dāng)前需要導(dǎo)出的類,我這里需要導(dǎo)出的是員工數(shù)據(jù),因此我將泛型設(shè)置為員工類,整體代碼如下:

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")//標(biāo)記此處的監(jiān)聽器為多例的,防止并發(fā)讀操作時(shí)出現(xiàn)錯(cuò)誤
public class EmployeeReadListener extends AnalysisEventListener<EmployeeBo> {

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

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

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

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

5.控制層

控制層負(fù)責(zé)接收前端傳過來的文件流,然后使用EasyExcel來對(duì)導(dǎo)入或者導(dǎo)出的數(shù)據(jù)進(jìn)行進(jìn)一步的處理,并把處理結(jié)果返回,需要注意的是,對(duì)于導(dǎo)出操作,該方法并沒有返回值,因此我們不需要返回值,而對(duì)于導(dǎo)入方法,此處我使用的是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è)務(wù)層
    @Autowired
    private EmployeeService service;
    /**
     *
     * @param file 獲得前端上傳的文件  EasyExcel.read 需要傳入三個(gè)參數(shù) 文件流 操作實(shí)體類的字節(jié)碼 監(jiān)聽器
     * @return 0 成功上傳
     * @throws IOException
     */
    @RequestMapping("read")
    @ResponseBody
    public ResultLayUi<String> readExcel(MultipartFile file) throws IOException {
        // 得到excel讀取對(duì)象  //通過文件獲得流, 獲得讀取文件的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("已成功導(dǎo)入");
        return resultLayUi;
    }
    @RequestMapping("write")
    public void writeExcel(String nos,HttpServletResponse response) throws IOException {
        //設(shè)置響應(yīng)頭
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        //導(dǎo)出的文件名
        String filename = URLEncoder.encode("員工信息","utf-8");
        //設(shè)置響應(yīng)頭
        response.setHeader("Content-Disposition","attachment;filename="+filename+".xlsx");
        //獲得流對(duì)象
        ServletOutputStream outputStream = response.getOutputStream();
        //獲得write對(duì)象
        ExcelWriterBuilder write = EasyExcel.write(outputStream, EmployeeBo.class);
        //獲得數(shù)據(jù)表對(duì)象
        ExcelWriterSheetBuilder sheet = write.sheet();
        //準(zhǔn)備需要輸出的數(shù)據(jù)   調(diào)用業(yè)務(wù)層,獲得所有需要導(dǎo)出的數(shù)據(jù)
        List<EmployeeBo> list = service.getExcelDataByNos(nos);
        //生成表格文件
        sheet.doWrite(list);
    }
}

6.前端代碼

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

下載:這里我使用了switch-case分支來對(duì)多個(gè)按鈕的事件進(jìn)行區(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>導(dǎo)出數(shù)據(jù)
      </button>
      <button class="layui-btn layui-btn-xs layui-btn-normal"  lay-event="read">
        <i class="layui-icon">&#xe613;</i>導(dǎo)入數(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('請(qǐng)至少選擇一行');
            } 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("確認(rèn)導(dǎo)出所有選中行嗎?", 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是一個(gè)DOM,注意:最好該元素要存放在body最外層,否則可能被其它的相對(duì)元素所影響
          });
            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秒關(guān)閉(如果不配置,默認(rèn)是3秒)
            }, function () {
              //關(guān)閉彈出層
              layer.closeAll();
              element.progress('demo', '0%'); //進(jìn)度條復(fù)位
            });
          }
        }
        //進(jìn)度條
        , progress: function (n, elem, e) {
          element.progress('demo', n + '%'); //可配合 layui 進(jìn)度條元素使用
          if (n == 100) {
            //layer.msg('上傳完畢', { icon: 1 });
          }
        }
      });

總結(jié)

EasyExcel是一個(gè)excel導(dǎo)入導(dǎo)出的解決方案,非常好用。

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

相關(guān)文章

最新評(píng)論