Java+EasyExcel實現文件的導入導出

引言

項目中需要Excel文件的導入與導出Excel並下載,例如,導入員工信息,導出員工信息,手動輸入比較繁瑣,所以本篇博文教大傢如何在Java中導入Excel文件與導出Excel文件

技術棧

Excel工具:EasyExcel

選用框架:Spring、Spring MVC、MyBatis(SSM)

項目構建管理工具:Maven

需求:

1.要求利用excel工具實現員工信息的導入與導出

2.導出要求為輸出到指定位置並下載

3.導入文件導入後,存入數據庫,並顯示在頁面

4.導出文件,點擊導出後寫入指定地址,並下載該文件

效果圖

項目結構

核心源碼

導入阿裡巴巴EasyExcel依賴

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>easyexcel</artifactId>
    <version>2.1.6</version>
</dependency>

這裡采用EasyExcel,為什麼不采用POI呢?

因為EasyExcel是對POI做的一個升級,POI相對於笨重,EasyExcel去除瞭一些POI比較繁瑣的東西,所以EasyExcel比較輕量級,所以本文采用EasyExcel

EasyExcel是阿裡巴巴的產品,POI是Apache基金會的開源產品,EasyExcel對POI做瞭一個升級

核心實體類

package com.wanshi.spring.entity;

import com.alibaba.excel.annotation.ExcelIgnore;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.write.style.ColumnWidth;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Employee {

    @ExcelIgnore
    private String noid;

    @ColumnWidth(20)
    @ExcelProperty("員工姓名")
    private String emp_name;

    @ColumnWidth(20)
    @ExcelProperty("員工年齡")
    private Integer emp_age;

    @ExcelIgnore
    private Integer emp_sex;

    //冗餘字段
    @ColumnWidth(20)
    @ExcelProperty("員工性別")
    private String str_emp_sex;

    @ColumnWidth(20)
    @ExcelProperty("員工工資")
    private Double emp_salary;

    @ColumnWidth(20)
    @ExcelProperty("員工住址")
    private String emp_address;

    @ColumnWidth(20)
    @ExcelProperty("員工崗位")
    private String emp_position;

    //分頁相關,當前頁與每頁的數據條數
    @ExcelIgnore
    private Integer pageNum;
    @ExcelIgnore
    private Integer pageSize;
}

核心監聽器類

EmployeeListener類:

package com.wanshi.spring.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.wanshi.spring.entity.Employee;

import java.util.ArrayList;
import java.util.List;

public class EmployeeReadListener extends AnalysisEventListener<Employee> {

    //員工集合
    private static List<Employee> employeeList = new ArrayList<>();

    // 每讀一樣,會調用該invoke方法一次
    @Override
    public void invoke(Employee data, AnalysisContext context) {
        employeeList.add(data);
        System.out.println("解析到一條數據:" + data);
    }

    // 全部讀完之後,會調用該方法
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        System.out.println("全部解析完成");
    }

    /**
     * 返回讀取到的員工集合
     * @return
     */
    public static List<Employee> getStudentList() {
        return employeeList;
    }
}

EasyExcel導入文件

Test測試類實現文件導入並存入數據庫

@Test
public void test1(){
    ExcelReaderBuilder workBook = EasyExcel.read
        ("C:\\Users\\王會稱\\Desktop\\員工.xlsx", Employee.class, new EmployeeReadListener());

    // 封裝工作表
    ExcelReaderSheetBuilder sheet1 = workBook.sheet();
    // 讀取
    sheet1.doRead();

    //寫入數據庫
    List<Employee> studentList = EmployeeReadListener.getStudentList();
    for (Employee employee : studentList) {
        employee.setNoid(PbSecretUtils.uuid());
        employeeMapper.insert(employee);
    }
}

通過頁面點擊導入文件並存入數據庫

EmployeeController類:

@PostMapping("/import_employee_excel")
public String importEmployeeExcel(MultipartFile emp_excel) {
    employeeService.importExcel(emp_excel);
    return "redirect:/employee/list";
}

EmployeeService類:

/**
     * 獲取用戶選擇的文件並將文件存入指定位置再將數據存入數據庫
     * @param emp_excel
     * @return
     */
public Integer importExcel(MultipartFile emp_excel) {
    try {
        String fileName = FileUploadUtil.upload(emp_excel, "");
        ExcelReaderBuilder workBook = EasyExcel.read
            (GlobalSet.upload_url+fileName, Employee.class, new EmployeeReadListener());

        // 封裝工作表
        ExcelReaderSheetBuilder sheet1 = workBook.sheet();
        // 讀取
        sheet1.doRead();

        List<Employee> studentList = EmployeeReadListener.getStudentList();
        for (Employee employee : studentList) {
            employee.setNoid(PbSecretUtils.uuid());
            if ("男".equals(employee.getStr_emp_sex())) {
                employee.setEmp_sex(1);
            } else {
                employee.setEmp_sex(2);
            }
            employeeMapper.insert(employee);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return 0;
}

EasyExcel導出文件

Test測試類導出文件到指定文件

@Test
public void test2() throws FileNotFoundException {

    List<Employee> employeeList = initData();


    ExcelWriterBuilder workBook = EasyExcel.write(GlobalSet.download_url, Employee.class);

    // sheet方法參數: 工作表的順序號(從0開始)或者工作表的名字
    workBook.sheet("測試數據表").doWrite(employeeList);
    System.out.println("寫入完成!");
}

/**
     * 生成測試數據
     * @return
     */
public List<Employee> initData() {
    List<Employee> employeeList = new ArrayList<>();
    for (int i = 1; i < 100; i++) {
        Employee employee = new Employee();
        employee.setEmp_name("小王說:"+i);
        employee.setEmp_age(19);
        if (i % 10 == 0) {
            employee.setEmp_sex(1);
        } else {
            employee.setEmp_sex(2);
        }
        employee.setEmp_salary(19999.00+i);
        employee.setEmp_address("北京市朝陽區"+i);
        employee.setEmp_position("Java高級工程師");
        employeeList.add(employee);
    }
    return employeeList;
}

通過頁面導出到指定文件後並下載文件

EmployeeController類

@GetMapping("/export_employee_excel")
    public void exportEmployeeExcel(HttpServletResponse response) {
        try {
            employeeService.exportEmployeeExcel(response);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

EmployeeService類:

public void exportEmployeeExcel(HttpServletResponse response) throws IOException {
        List<Employee> kspwStudentSeatList = list();
        try {
            ExcelWriterBuilder workBook = EasyExcel.write(GlobalSet.download_url, Employee.class);
            // sheet方法參數: 工作表的順序號(從0開始)或者工作表的名字
            workBook.sheet("員工信息").doWrite(kspwStudentSeatList);
            downloadTempalate(response);
            System.out.println("寫入完成!");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 下載文件
     * @param response
     * @throws IOException
     */
    public static void downloadTempalate(HttpServletResponse response) throws IOException {
        // 告訴瀏覽器用什麼軟件可以打開此文件
        response.setHeader("content-Type", "application/vnd.ms-excel");
        // 下載文件的默認名稱
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("員工信息.xlsx", "utf-8"));
        //4. 創建輸入、輸出流
        FileInputStream input = new FileInputStream(GlobalSet.download_url);
        ServletOutputStream sos = response.getOutputStream();

        //IO流獲取文件的字節流,然後再響應給瀏覽器
        byte[] arr = new byte[1024];
        int res = 0;
        while((res = input.read(arr)) > 0){
            //將讀取的內容輸出到輸出流中
            sos.write(arr, 0, res);
        }

        input.close();
        sos.close();
    } 

以上就是Java+EasyExcel實現文件的導入導出的詳細內容,更多關於Java EasyExcel文件的導入導出的資料請關註WalkonNet其它相關文章!

推薦閱讀: